onnx2tengine.cpp 82.0 KB
Newer Older
T
Thunder 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * License); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*
 * Copyright (c) 2021, OPEN AI LAB
 * Author: xlchen@openailab.com
B
bzhang5 已提交
23
           bzhang@openailab.com
T
Thunder 已提交
24 25 26 27
 */

#include "onnx2tengine.hpp"

B
bzhang5 已提交
28 29 30 31
/*
*   SELF DEFINE VARIABLE
*   FOR ONNX SERIALIZER
*/
N
nihui 已提交
32
const int OP_VERSION = 1;
T
Thunder 已提交
33
static int op_set;
T
Thunder 已提交
34

B
bzhang5 已提交
35 36 37
/*
*   ASSIST FUNCTIONS FOR ONNX SERIALIZER START
*/
B
bzhang5 已提交
38
bool onnx_serializer::find_op_load_method(const std::string& op_name)
T
Thunder 已提交
39
{
N
nihui 已提交
40
    if (op_load_map.count(op_name))
T
Thunder 已提交
41 42 43 44 45 46 47 48 49 50 51
        return true;

    return false;
}

ir_tensor_t* find_tensor(ir_graph_t* graph, const std::string& tensor_name)
{
    for (uint16_t i = 0; i < graph->tensor_num; i++)
    {
        ir_tensor_t* tensor = get_ir_graph_tensor(graph, i);
        if (tensor->name == tensor_name)
T
Thunder 已提交
52
        {
T
Thunder 已提交
53
            return tensor;
N
nihui 已提交
54
        }
T
Thunder 已提交
55
    }
N
nihui 已提交
56

T
Thunder 已提交
57 58 59
    return nullptr;
}

T
Thunder 已提交
60
static int change_node_op(ir_node_t* node, int new_op_type)
B
bzhang5 已提交
61 62 63 64 65 66 67 68 69 70 71 72
{
    sys_free(node->op.param_mem);
    node->op.type = new_op_type;
    ir_method_t* ir_method = find_op_method(new_op_type, OP_VERSION);
    if ((NULL != ir_method) && (NULL != ir_method->init) && (ir_method->init(&node->op) < 0))
    {
        return -1;
    }

    return 0;
}

T
Thunder 已提交
73 74 75 76 77
const int get_onnx_tensor_data_type(const onnx::TensorProto& onnx_tensor)
{
    int tensor_data_type = -1;
    switch (onnx_tensor.data_type())
    {
N
nihui 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    case 1:
        tensor_data_type = TENGINE_DT_FP32;
        break;
    case 2:
        tensor_data_type = TENGINE_DT_UINT8;
        break;
    case 3:
        tensor_data_type = TENGINE_DT_INT8;
        break;
    case 5:
        tensor_data_type = TENGINE_DT_INT16;
        break;
    case 6: // int 32
    case 7: // int 64
        tensor_data_type = TENGINE_DT_INT32;
        break;
    case 10:
        tensor_data_type = TENGINE_DT_FP16;
        break;

    default:
        fprintf(stderr, "tensor: %s. data type unsupported in get data type: %d.\n", onnx_tensor.name().c_str(), onnx_tensor.data_type());
        return -1;
T
Thunder 已提交
101 102 103 104 105
    }

    return tensor_data_type;
}

B
bzhang5 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
onnx::TensorProto get_node_attr_tensor(const onnx::NodeProto& node, const char* key)
{
    for (int i = 0; i < node.attribute_size(); i++)
    {
        const onnx::AttributeProto& attr = node.attribute(i);
        if (attr.name() == key)
        {
            return attr.t();
        }
    }

    return onnx::TensorProto();
}

/*
*   ASSIST FUNCTIONS FOR ONNX SERIALIZER END
*/

N
nihui 已提交
124
int onnx_serializer::load_model_file(std::string model_file, onnx::ModelProto& model)
T
Thunder 已提交
125 126 127
{
    std::ifstream is(model_file, std::ios::in | std::ios::binary);

N
nihui 已提交
128
    if (!is.is_open())
T
Thunder 已提交
129
    {
T
Thunder 已提交
130
        fprintf(stderr, "cannot open file: %s \n", model_file.c_str());
T
Thunder 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
        return -1;
    }

    google::protobuf::io::IstreamInputStream input_stream(&is);
    google::protobuf::io::CodedInputStream coded_input(&input_stream);

#if GOOGLE_PROTOBUF_VERSION >= 3011000
    coded_input.SetTotalBytesLimit(INT_MAX);
#else
    coded_input.SetTotalBytesLimit(INT_MAX, INT_MAX / 2);
#endif

    bool ret = model.ParseFromCodedStream(&coded_input);

    is.close();

N
nihui 已提交
147
    if (!ret)
T
Thunder 已提交
148
    {
T
Thunder 已提交
149
        fprintf(stderr, "onnx serializer: parse file: %s \n", model_file.c_str());
T
Thunder 已提交
150 151 152
        return -1;
    }

T
Thunder 已提交
153 154 155 156 157 158 159 160 161 162 163 164
    /* get model op set */
    op_set = -1;
    if (model.opset_import_size())
    {
        const onnx::OperatorSetIdProto opset_import = model.opset_import(0);
        if (opset_import.has_version())
        {
            op_set = opset_import.version();
        }
    }
    if (op_set != -1)
    {
T
Thunder 已提交
165
        fprintf(stderr, "Model op set is: %d\n", op_set);
T
Thunder 已提交
166 167
    }

T
Thunder 已提交
168 169
    return 0;
}
B
bzhang5 已提交
170

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
#define TASSERT(x)                                \
    if (!(x))                                     \
    {                                             \
        throw std::runtime_error("check failed"); \
    }

// this class is used to force the user to explicitly specify the template argument type
// of GetAttributeOrDefault
// Ref: https://stackoverflow.com/a/28171644
template<typename T>
struct Identity
{
    using type = T;
};

class NoAttrWithGivenNameError : public std::runtime_error
{
public:
    explicit NoAttrWithGivenNameError(const std::string& msg)
        : std::runtime_error(msg)
    {
    }
};

template<typename T>
T GetAttributeOrThrow(const onnx::NodeProto& node, const std::string& name);

template<typename T>
T GetAttributeOrDefault(const onnx::NodeProto& node, const std::string& name, typename Identity<T>::type default_val);

#define DEFINE_GetAttribute_FOR_SCALAR(cpp_type, onnx_proto_type, onnx_attr_getter) \
    template<>                                                                      \
    cpp_type GetAttributeOrThrow<cpp_type>(const onnx::NodeProto& node,             \
                                           const std::string& name)                 \
    {                                                                               \
        for (int k = 0; k < node.attribute_size(); k++)                             \
        {                                                                           \
            const onnx::AttributeProto& attr = node.attribute(k);                   \
                                                                                    \
            if (attr.name() == name)                                                \
            {                                                                       \
                if (attr.type() != onnx::AttributeProto::onnx_proto_type)           \
                {                                                                   \
                    throw std::invalid_argument(                                    \
                        "the type of attr " + name + " is "                         \
                        + onnx::AttributeProto::AttributeType_Name(attr.type())     \
                        + ", expected "                                             \
                        + onnx::AttributeProto::AttributeType_Name(                 \
                            onnx::AttributeProto::onnx_proto_type));                \
                }                                                                   \
                return attr.onnx_attr_getter();                                     \
            }                                                                       \
        }                                                                           \
        throw NoAttrWithGivenNameError("cannot find attr " + name);                 \
    }                                                                               \
    template<>                                                                      \
    cpp_type GetAttributeOrDefault<cpp_type>(                                       \
        const onnx::NodeProto& node, const std::string& name, cpp_type default_val) \
    {                                                                               \
        try                                                                         \
        {                                                                           \
            return GetAttributeOrThrow<cpp_type>(node, name);                       \
        }                                                                           \
        catch (const NoAttrWithGivenNameError&)                                     \
        {                                                                           \
            return default_val;                                                     \
        }                                                                           \
    }

DEFINE_GetAttribute_FOR_SCALAR(float, FLOAT, f);
DEFINE_GetAttribute_FOR_SCALAR(int, INT, i);
DEFINE_GetAttribute_FOR_SCALAR(std::string, STRING, s);

#undef DEFINE_GetAttribute_FOR_SCALAR

#define DEFINE_GetAttribute_FOR_VECTOR(cpp_type, onnx_proto_type, onnx_attr_getter) \
    template<>                                                                      \
    cpp_type GetAttributeOrThrow<cpp_type>(const onnx::NodeProto& node,             \
                                           const std::string& name)                 \
    {                                                                               \
        for (int k = 0; k < node.attribute_size(); k++)                             \
        {                                                                           \
            const onnx::AttributeProto& attr = node.attribute(k);                   \
                                                                                    \
            if (attr.name() == name)                                                \
            {                                                                       \
                if (attr.type() != onnx::AttributeProto::onnx_proto_type)           \
                {                                                                   \
                    throw std::invalid_argument(                                    \
                        "the type of attr " + name + " is "                         \
                        + onnx::AttributeProto::AttributeType_Name(attr.type())     \
                        + ", expected "                                             \
                        + onnx::AttributeProto::AttributeType_Name(                 \
                            onnx::AttributeProto::onnx_proto_type));                \
                }                                                                   \
                cpp_type res;                                                       \
                auto size = attr.onnx_attr_getter##_size();                         \
                for (int i = 0; i < size; i++)                                      \
                {                                                                   \
                    res.push_back(attr.onnx_attr_getter(i));                        \
                }                                                                   \
                return res;                                                         \
            }                                                                       \
        }                                                                           \
        throw NoAttrWithGivenNameError("cannot find attr " + name);                 \
    }                                                                               \
    template<>                                                                      \
    cpp_type GetAttributeOrDefault<cpp_type>(                                       \
        const onnx::NodeProto& node, const std::string& name, cpp_type default_val) \
    {                                                                               \
        try                                                                         \
        {                                                                           \
            return GetAttributeOrThrow<cpp_type>(node, name);                       \
        }                                                                           \
        catch (const NoAttrWithGivenNameError&)                                     \
        {                                                                           \
            return default_val;                                                     \
        }                                                                           \
    }

DEFINE_GetAttribute_FOR_VECTOR(std::vector<float>, FLOATS, floats);
DEFINE_GetAttribute_FOR_VECTOR(std::vector<int>, INTS, ints);

#undef DEFINE_GetAttribute_FOR_VECTOR

B
bzhang5 已提交
296
int onnx_serializer::load_constant_tensor(ir_graph_t* graph, const onnx::GraphProto& onnx_graph)
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
{
    std::map<std::string, onnx::TensorProto> node_tensor;
    int node_count = onnx_graph.node_size();

    for (int i = 0; i < node_count; i++)
    {
        const onnx::NodeProto& node = onnx_graph.node(i);
        const std::string& op = node.op_type();
        if (op == "Constant")
        {
            onnx::TensorProto node_attr = get_node_attr_tensor(node, "value");
            node_tensor.insert(std::pair<std::string, onnx::TensorProto>(node.output(0), node_attr));
        }
    }
    if (node_tensor.size() == 0)
    {
        return 0;
    }
    for (int i = 0; i < node_count; i++)
    {
        const onnx::NodeProto& node = onnx_graph.node(i);

        const std::string& op = node.op_type();
320
        bool logged = false;
321

322
        if (node.input_size() > 1)
N
nihui 已提交
323
        {
324
            // iter over constant inputs and create ir_tensor for constant tensor
F
FeiGeChuanShu 已提交
325
            for (int inp_idx = 0; inp_idx < node.input_size(); ++inp_idx)
T
Thunder 已提交
326
            {
327 328
                if (node_tensor.count(node.input(inp_idx)) == 0)
                    continue;
329 330
                if (!logged)
                {
331 332
                    logged = true;
                    if (!(op == "Reshape" || op == "Gather" || op == "Div" || op == "Resize" || op == "Upsample"
333 334
                          || op == "Clip" || op == "Slice" || op == "Expand"))
                    {
335 336 337 338
                        auto msg = "Load a Constant node \"%s\" as input[%d] of node \"%s\".\n";
                        printf(msg, node.input(inp_idx).c_str(), inp_idx, node.name().c_str());
                    }
                }
339 340 341 342 343 344 345 346
                const onnx::TensorProto& onnx_tensor = node_tensor[node.input(inp_idx)];
                std::pair<std::string, bool> t(node.input(inp_idx), 0);
                tensor_check.insert(t);
                int tensor_data_type = get_onnx_tensor_data_type(onnx_tensor);
                if (tensor_data_type < 0)
                {
                    return -1;
                }
N
nihui 已提交
347

348 349 350 351 352 353 354
                const char* name = node.input(inp_idx).c_str();
                int dim_num = onnx_tensor.dims_size();
                std::vector<int> dims(dim_num);
                for (int j = 0; j < dim_num; j++)
                {
                    dims[j] = onnx_tensor.dims(j);
                }
355

356 357 358
                // create ir tensor
                ir_tensor_t* ir_tensor = create_ir_tensor(graph, name, tensor_data_type);
                if (ir_tensor == NULL)
359
                {
360 361
                    fprintf(stderr, "create ir tensor failed!\n");
                    return -1;
N
nihui 已提交
362
                }
363 364 365 366
                set_ir_tensor_shape(ir_tensor, dims.data(), dim_num);
                ir_tensor->tensor_type = TENSOR_TYPE_CONST;
                // set tensor data
                if (7 == onnx_tensor.data_type())
367
                {
368 369 370 371
                    int tensor_size = ir_tensor->elem_num * sizeof(int64_t);
                    ir_tensor->data = sys_malloc(tensor_size);
                    int64_t* mem_buf = (int64_t*)ir_tensor->data;
                    if (onnx_tensor.has_raw_data())
B
bzhang5 已提交
372
                    {
373 374 375 376 377
                        int64_t* raw_data = (int64_t*)onnx_tensor.raw_data().data();
                        for (int j = 0; j < ir_tensor->elem_num; j++)
                        {
                            mem_buf[j] = raw_data[j];
                        }
B
bzhang5 已提交
378
                    }
379
                    else
380
                    {
381 382 383 384 385
                        int64_t* raw_data = (int64_t*)onnx_tensor.int64_data().data();
                        for (int j = 0; j < ir_tensor->elem_num; j++)
                        {
                            mem_buf[j] = raw_data[j];
                        }
386 387
                    }
                }
F
FeiGeChuanShu 已提交
388
                else if (tensor_data_type == TENGINE_DT_FP32)
389
                {
390 391 392 393 394
                    // to support float type constant data loading
                    int tensor_size = ir_tensor->elem_num * sizeof(float_t);
                    ir_tensor->data = sys_malloc(tensor_size);
                    float_t* mem_buf = (float_t*)ir_tensor->data;
                    if (onnx_tensor.has_raw_data())
395
                    {
396 397 398 399 400
                        float_t* raw_data = (float_t*)onnx_tensor.raw_data().data();
                        for (int j = 0; j < ir_tensor->elem_num; j++)
                        {
                            mem_buf[j] = raw_data[j];
                        }
401
                    }
402
                    else
B
bzhang5 已提交
403
                    {
404 405 406 407 408
                        int32_t* raw_data = (int32_t*)onnx_tensor.int32_data().data();
                        for (int j = 0; j < ir_tensor->elem_num; j++)
                        {
                            mem_buf[j] = raw_data[j];
                        }
B
bzhang5 已提交
409
                    }
410
                }
B
bzhang5 已提交
411
                else
412
                {
413 414 415 416 417 418 419 420 421 422 423 424
                    int tensor_size = ir_tensor->elem_num * sizeof(uint8_t);
                    ir_tensor->data = sys_malloc(tensor_size);
                    uint8_t* mem_buf = (uint8_t*)ir_tensor->data;
                    if (onnx_tensor.has_raw_data())
                    {
                        uint8_t* raw_data = (uint8_t*)onnx_tensor.raw_data().data();
                        for (int j = 0; j < ir_tensor->elem_num; j++)
                        {
                            mem_buf[j] = raw_data[j];
                        }
                    }
                    else
B
bzhang5 已提交
425
                    {
426 427 428 429 430
                        uint8_t* raw_data = (uint8_t*)onnx_tensor.int32_data().data();
                        for (int j = 0; j < ir_tensor->elem_num; j++)
                        {
                            mem_buf[j] = raw_data[j];
                        }
B
bzhang5 已提交
431
                    }
432
                }
433 434
                ir_node_t* ir_node = create_ir_node(graph, name, OP_CONST, OP_VERSION);
                set_ir_node_output_tensor(ir_node, 0, ir_tensor);
435 436 437
            }
        }
    }
N
nihui 已提交
438

439 440 441
    return 0;
}

B
bzhang5 已提交
442
int onnx_serializer::load_initializer_tensor(ir_graph_t* graph, const onnx::GraphProto& onnx_graph)
T
Thunder 已提交
443 444 445 446 447
{
    int const_tensor_num = onnx_graph.initializer_size();
    for (int i = 0; i < const_tensor_num; i++)
    {
        const onnx::TensorProto& onnx_tensor = onnx_graph.initializer(i);
N
nihui 已提交
448

T
Thunder 已提交
449 450 451 452 453 454
        if (onnx_tensor.data_type() != 1 && onnx_tensor.data_type() != 6 && onnx_tensor.data_type() != 7) // fp32 int32 int64
        {
            fprintf(stderr, "const tensor data type is not fp32 or int32 or int64. \n");
            fprintf(stderr, "onnx_tensor.data_type: %d \n", onnx_tensor.data_type());
            return -1;
        }
B
bzhang5 已提交
455 456
        std::pair<std::string, int> t(onnx_tensor.name(), 0);
        tensor_check.insert(t);
T
Thunder 已提交
457 458 459 460 461
        int tensor_data_type = get_onnx_tensor_data_type(onnx_tensor);
        if (tensor_data_type < 0)
        {
            return -1;
        }
T
Thunder 已提交
462 463
        const char* name = onnx_tensor.name().c_str();
        int dim_num = onnx_tensor.dims_size();
T
Thunder 已提交
464
        std::vector<int> dims(dim_num);
T
Thunder 已提交
465 466 467 468 469 470
        for (int j = 0; j < dim_num; j++)
        {
            dims[j] = onnx_tensor.dims(j);
        }

        // create ir tensor
T
Thunder 已提交
471
        ir_tensor_t* ir_tensor = create_ir_tensor(graph, name, tensor_data_type);
T
Thunder 已提交
472 473 474 475 476
        if (ir_tensor == NULL)
        {
            fprintf(stderr, "create ir tensor failed!\n");
            return -1;
        }
T
Thunder 已提交
477
        set_ir_tensor_shape(ir_tensor, dims.data(), dim_num);
T
Thunder 已提交
478
        ir_tensor->tensor_type = TENSOR_TYPE_CONST;
479 480 481 482 483
        if (ir_tensor->dim_num == 0)
        {
            ir_tensor->dim_num = 1;
            ir_tensor->dims[0] = 1;
        }
N
nihui 已提交
484

T
Thunder 已提交
485 486 487 488
        if (onnx_tensor.has_raw_data())
        {
            if (onnx_tensor.data_type() == 1) //fp32
            {
T
Thunder 已提交
489
                ir_tensor->data_type = TENGINE_DT_FP32;
N
nihui 已提交
490
                int tensor_size = ir_tensor->elem_num * sizeof(float);
B
bzhang5 已提交
491
                ir_tensor->data = sys_malloc(tensor_size);
B
bzhang5 已提交
492 493
                float* mem_buf = (float*)ir_tensor->data;
                float* raw_data = (float*)onnx_tensor.raw_data().c_str();
B
bzhang5 已提交
494 495 496 497
                for (int j = 0; j < ir_tensor->elem_num; j++)
                {
                    mem_buf[j] = raw_data[j];
                }
T
Thunder 已提交
498
            }
T
Thunder 已提交
499 500
            else if (onnx_tensor.data_type() == 6) // int32
            {
T
Thunder 已提交
501
                ir_tensor->data_type = TENGINE_DT_INT32;
N
nihui 已提交
502
                int tensor_size = ir_tensor->elem_num * sizeof(int32_t);
T
Thunder 已提交
503 504 505 506 507 508 509 510 511
                ir_tensor->data = sys_malloc(tensor_size);
                int32_t* mem_buf = (int32_t*)ir_tensor->data;
                int32_t* raw_data = (int32_t*)onnx_tensor.raw_data().data();
                for (int j = 0; j < ir_tensor->elem_num; j++)
                {
                    mem_buf[j] = raw_data[j];
                }
            }
            else if (onnx_tensor.data_type() == 7) // int64
T
Thunder 已提交
512
            {
T
Thunder 已提交
513
                // ir_tensor->data_type = TENGINE_DT_INT32;
N
nihui 已提交
514
                int tensor_size = ir_tensor->elem_num * sizeof(int64_t);
B
bzhang5 已提交
515 516 517 518 519 520 521
                ir_tensor->data = sys_malloc(tensor_size);
                int64_t* mem_buf = (int64_t*)ir_tensor->data;
                int64_t* raw_data = (int64_t*)onnx_tensor.raw_data().data();
                for (int j = 0; j < ir_tensor->elem_num; j++)
                {
                    mem_buf[j] = raw_data[j];
                }
T
Thunder 已提交
522
            }
T
Thunder 已提交
523 524 525 526 527
            else
            {
                fprintf(stderr, "tensor: %s data type unsupported in set raw data.\n", onnx_tensor.name().c_str());
                return -1;
            }
T
Thunder 已提交
528 529 530 531 532
        }
        else
        {
            if (onnx_tensor.data_type() == 1) //fp32
            {
T
Thunder 已提交
533
                ir_tensor->data_type = TENGINE_DT_FP32;
B
bzhang5 已提交
534 535 536 537 538 539 540 541
                int tensor_size = ir_tensor->elem_num * sizeof(float);
                ir_tensor->data = sys_malloc(tensor_size);
                float* mem_buf = (float*)ir_tensor->data;
                float* raw_data = (float*)onnx_tensor.float_data().data();
                for (int j = 0; j < ir_tensor->elem_num; j++)
                {
                    mem_buf[j] = raw_data[j];
                }
T
Thunder 已提交
542
            }
T
Thunder 已提交
543
            else if (onnx_tensor.data_type() == 6) // int32
T
Thunder 已提交
544
            {
T
Thunder 已提交
545
                ir_tensor->data_type = TENGINE_DT_INT32;
B
bzhang5 已提交
546 547 548 549 550 551 552 553
                int tensor_size = ir_tensor->elem_num * sizeof(int32_t);
                ir_tensor->data = sys_malloc(tensor_size);
                int32_t* mem_buf = (int32_t*)ir_tensor->data;
                int32_t* raw_data = (int32_t*)onnx_tensor.int32_data().data();
                for (int j = 0; j < ir_tensor->elem_num; j++)
                {
                    mem_buf[j] = raw_data[j];
                }
T
Thunder 已提交
554
            }
T
Thunder 已提交
555 556
            else if (onnx_tensor.data_type() == 7) // int64
            {
T
Thunder 已提交
557
                // ir_tensor->data_type = TENGINE_DT_INT32;
T
Thunder 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571
                int tensor_size = ir_tensor->elem_num * sizeof(int64_t);
                ir_tensor->data = sys_malloc(tensor_size);
                int64_t* mem_buf = (int64_t*)ir_tensor->data;
                int64_t* raw_data = (int64_t*)onnx_tensor.int64_data().data();
                for (int j = 0; j < ir_tensor->elem_num; j++)
                {
                    mem_buf[j] = raw_data[j];
                }
            }
            else
            {
                fprintf(stderr, "tensor: %s data type unsupported in set data.\n", onnx_tensor.name().c_str());
                return -1;
            }
T
Thunder 已提交
572
        }
N
nihui 已提交
573

T
Thunder 已提交
574 575 576 577 578 579
        ir_node_t* ir_node = create_ir_node(graph, name, OP_CONST, OP_VERSION);
        set_ir_node_output_tensor(ir_node, 0, ir_tensor);
    }
    return 0;
}

B
bzhang5 已提交
580
int onnx_serializer::set_graph_input(ir_graph_t* graph, const onnx::GraphProto& onnx_graph)
T
Thunder 已提交
581 582 583 584 585
{
    std::vector<int16_t> input_nodes;
    for (int i = 0; i < onnx_graph.input_size(); i++)
    {
        const onnx::ValueInfoProto& val = onnx_graph.input(i);
N
nihui 已提交
586
        if (get_ir_tensor_index_from_name(graph, val.name().c_str()) != -1)
T
Thunder 已提交
587 588 589 590 591 592 593
            continue;

        // now, catch an input tensor
        const onnx::TypeProto& type = val.type();
        const onnx::TypeProto::Tensor& tensor_type = type.tensor_type();
        const onnx::TensorShapeProto& shape = tensor_type.shape();
        int has_shape = 1;
T
Thunder 已提交
594
        std::vector<int> dims(shape.dim_size());
N
nihui 已提交
595
        for (int j = 0; j < shape.dim_size(); j++)
T
Thunder 已提交
596 597
        {
            const onnx::TensorShapeProto::Dimension& dim = shape.dim(j);
N
nihui 已提交
598
            if (dim.has_dim_param())
T
Thunder 已提交
599 600 601 602 603 604 605 606 607
            {
                has_shape = 0;
                break;
            }
            dims[j] = dim.dim_value();
        }

        ir_tensor_t* tensor = create_ir_tensor(graph, val.name().c_str(), TENGINE_DT_FP32);
        if (has_shape)
T
Thunder 已提交
608
        {
T
Thunder 已提交
609
            set_ir_tensor_shape(tensor, dims.data(), shape.dim_size());
T
Thunder 已提交
610 611
        }
        tensor->tensor_type = TENSOR_TYPE_INPUT;
T
Thunder 已提交
612 613 614 615 616
        ir_node_t* node = create_ir_node(graph, val.name().c_str(), OP_INPUT, OP_VERSION);
        set_ir_node_output_tensor(node, 0, tensor);
        input_nodes.push_back(node->index);
    }

T
Thunder 已提交
617
    set_ir_graph_input_node(graph, input_nodes.data(), input_nodes.size());
T
Thunder 已提交
618 619 620
    return 0;
}

B
bzhang5 已提交
621
int onnx_serializer::load_graph_node(ir_graph_t* graph, const onnx::GraphProto& onnx_graph)
T
Thunder 已提交
622 623 624
{
    int i;
    std::vector<std::string> no_supported_op;
N
nihui 已提交
625
    for (i = 0; i < onnx_graph.node_size(); i++)
T
Thunder 已提交
626 627 628 629
    {
        const onnx::NodeProto& onnx_node = onnx_graph.node(i);
        const std::string& onnx_op_name = onnx_node.op_type();

N
nihui 已提交
630
        if (!find_op_load_method(onnx_op_name))
T
Thunder 已提交
631
        {
N
nihui 已提交
632 633
            auto it = find(no_supported_op.begin(), no_supported_op.end(), onnx_op_name);
            if (it == no_supported_op.end())
T
Thunder 已提交
634
            {
N
nihui 已提交
635
                if (onnx_op_name == "Constant")
T
Thunder 已提交
636 637 638 639 640
                    continue;
                no_supported_op.push_back(onnx_op_name);
            }
        }
    }
N
nihui 已提交
641
    if (no_supported_op.size())
T
Thunder 已提交
642
    {
T
Thunder 已提交
643
        fprintf(stderr, "These %zu op are not supported\n{ ", no_supported_op.size());
N
nihui 已提交
644
        for (int j = 0; j < (int)no_supported_op.size(); j++)
T
Thunder 已提交
645
        {
T
Thunder 已提交
646
            fprintf(stderr, "%s ", no_supported_op[j].c_str());
T
Thunder 已提交
647
        }
T
Thunder 已提交
648
        fprintf(stderr, "}\n");
T
Thunder 已提交
649 650 651
        return -1;
    }

N
nihui 已提交
652
    for (i = 0; i < onnx_graph.node_size(); i++)
T
Thunder 已提交
653 654 655 656 657
    {
        /* create ir node*/
        const onnx::NodeProto& onnx_node = onnx_graph.node(i);
        const std::string& op_name = onnx_node.op_type();
        if (op_name == "Constant")
T
Thunder 已提交
658
        {
T
Thunder 已提交
659
            continue;
T
Thunder 已提交
660
        }
661 662
        std::string node_name = onnx_node.name();
        if (node_name.empty())
T
Thunder 已提交
663
        {
664
            node_name = std::to_string(i);
T
Thunder 已提交
665
        }
T
Thunder 已提交
666 667
        ir_node_t* ir_node = create_ir_node(graph, node_name.c_str(), op_load_map[op_name].first, OP_VERSION);
        if (ir_node == NULL)
T
Thunder 已提交
668
        {
T
Thunder 已提交
669
            return -1;
T
Thunder 已提交
670
        }
T
Thunder 已提交
671 672 673 674
        /* set ir node io */
        for (int j = 0; j < onnx_node.input_size(); j++)
        {
            const std::string& input_name = onnx_node.input(j);
B
bzhang5 已提交
675 676 677 678
            if (input_name == "")
            {
                continue;
            }
T
Thunder 已提交
679
            int tensor_id = get_ir_tensor_index_from_name(graph, input_name.c_str());
N
nihui 已提交
680
            ir_tensor_t* tensor = get_ir_graph_tensor(graph, tensor_id);
681
            tensor_check[tensor->name] = tensor_check[tensor->name] + 1;
T
Thunder 已提交
682
            set_ir_node_input_tensor(ir_node, ir_node->input_num, tensor);
T
Thunder 已提交
683
        }
B
bzhang5 已提交
684

T
Thunder 已提交
685 686 687
        for (int j = 0; j < onnx_node.output_size(); j++)
        {
            if (op_name == "Dropout" && j > 0)
T
Thunder 已提交
688
            {
T
Thunder 已提交
689
                continue;
T
Thunder 已提交
690
            }
T
Thunder 已提交
691 692 693 694 695 696 697 698
            const std::string& output_name = onnx_node.output(j);
            ir_tensor_t* tensor = create_ir_tensor(graph, output_name.c_str(), TENGINE_DT_FP32);
            set_ir_node_output_tensor(ir_node, j, tensor);
        }
        /* exec op load func */
        op_load_t loader = op_load_map[op_name].second;
        if (loader(graph, ir_node, onnx_node) < 0)
        {
T
Thunder 已提交
699
            fprintf(stderr, "load op %s func failed in node %s .\n", op_name.c_str(), node_name.c_str());
T
Thunder 已提交
700 701 702 703 704 705
            return -1;
        }
    }
    return 0;
}

B
bzhang5 已提交
706
int onnx_serializer::set_graph_output(ir_graph_t* graph, const onnx::GraphProto& onnx_graph)
T
Thunder 已提交
707 708 709 710 711
{
    std::vector<int16_t> output_nodes;
    for (int i = 0; i < onnx_graph.output_size(); i++)
    {
        const onnx::ValueInfoProto& val = onnx_graph.output(i);
712 713 714 715 716 717
        int tensor_id = get_ir_tensor_index_from_name(graph, val.name().c_str());

        const onnx::TypeProto& type = val.type();
        const onnx::TypeProto::Tensor& tensor_type = type.tensor_type();
        const onnx::TensorShapeProto& shape = tensor_type.shape();
        int has_shape = 1;
T
Thunder 已提交
718
        std::vector<int> dims(shape.dim_size());
N
nihui 已提交
719
        for (int j = 0; j < shape.dim_size(); j++)
T
Thunder 已提交
720
        {
721
            const onnx::TensorShapeProto::Dimension& dim = shape.dim(j);
N
nihui 已提交
722
            if (dim.has_dim_param())
723 724 725 726 727
            {
                has_shape = 0;
                break;
            }
            dims[j] = dim.dim_value();
T
Thunder 已提交
728
        }
729 730
        ir_tensor_t* tensor = get_ir_graph_tensor(graph, tensor_id);
        if (has_shape)
T
Thunder 已提交
731
        {
T
Thunder 已提交
732
            set_ir_tensor_shape(tensor, dims.data(), shape.dim_size());
T
Thunder 已提交
733
        }
734
        ir_node_t* node = get_ir_graph_node(graph, tensor->producer);
735
        output_nodes.push_back(node->index);
T
Thunder 已提交
736
    }
T
Thunder 已提交
737 738

    std::vector<int16_t> node_idx;
T
Thunder 已提交
739 740
    for (int i = 0; i < output_nodes.size(); i++)
    {
T
Thunder 已提交
741
        node_idx.push_back(output_nodes[i]);
T
Thunder 已提交
742
    }
T
Thunder 已提交
743 744 745 746
    set_ir_graph_output_node(graph, node_idx.data(), output_nodes.size());
    return 0;
}

T
Thunder 已提交
747
static int deal_old_softmax(ir_graph_t* graph)
T
Thunder 已提交
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
{
    std::vector<ir_node_t*> old_spec_softmax_nodes;

    // get all softmax case.
    if (op_set < 13)
    {
        int node_num = graph->node_num;
        for (int i = 0; i < node_num; ++i)
        {
            ir_node_t* node = get_ir_graph_node(graph, i);
            if (node->op.type != OP_SOFTMAX)
            {
                continue;
            }
            struct softmax_param* param = (struct softmax_param*)node->op.param_mem;
            // check if transpose + softmax + transpose
            ir_tensor_t* input = get_ir_graph_tensor(graph, node->input_tensors[0]);
            ir_tensor_t* output = get_ir_graph_tensor(graph, node->output_tensors[0]);
            ir_node_t* pre_node = get_ir_graph_node(graph, input->producer);
            ir_node_t* next_node = nullptr;
            if (output->consumer_num > 0)
            {
                next_node = get_ir_graph_node(graph, output->consumer[0]);
            }
            if (next_node != nullptr && pre_node->op.type == OP_TRANSPOSE && next_node->op.type == OP_TRANSPOSE)
            {
                if (param->axis == input->dim_num - 1)
                {
                    // TODO: optimize to softmax(new spec).
                    continue;
                }
                else
                {
                    continue;
                }
            }
            if (param->axis == input->dim_num - 1)
            {
                // old spec == new spec
                continue;
            }

            old_spec_softmax_nodes.push_back(node);
        }
    }

    // support old spec onnx softmax.
    for (auto& node : old_spec_softmax_nodes)
    {
        ir_tensor_t* input = get_ir_graph_tensor(graph, node->input_tensors[0]);
        struct softmax_param* param = (struct softmax_param*)node->op.param_mem;

        // support old spec by adding reshape node.
        // reshape in
        std::string node_name = node->name;
        std::string name = node_name + "_reshape_in";
        int reshape_in_id = add_node_above(graph, node->index, OP_RESHAPE, name.c_str());
        ir_node_t* reshape_in = get_ir_graph_node(graph, reshape_in_id);
        struct reshape_param* reshape_in_param = (struct reshape_param*)reshape_in->op.param_mem;

        std::vector<int> re_shape;
        for (int j = 0; j < input->dim_num; ++j)
        {
            if (j == param->axis)
            {
                re_shape.push_back(-1);
                break;
            }
            re_shape.push_back(input->dims[j]);
        }
        reshape_in_param->is_onnx = 1;
        reshape_in_param->dim_size = re_shape.size();
        reshape_in_param->re_shape = (int*)sys_malloc(reshape_in_param->dim_size * sizeof(int));
        for (int j = 0; j < reshape_in_param->dim_size; ++j)
        {
            reshape_in_param->re_shape[j] = re_shape[j];
        }

        // reshape out
        name = node_name + "_reshape_out";
        int reshape_out_id = add_node_below(graph, node->index, OP_RESHAPE, name.c_str());
        ir_node_t* reshape_out = get_ir_graph_node(graph, reshape_out_id);
        struct reshape_param* reshape_out_param = (struct reshape_param*)reshape_out->op.param_mem;
        reshape_out_param->is_onnx = 1;
        reshape_out_param->dim_size = input->dim_num;
        reshape_out_param->re_shape = (int*)sys_malloc(reshape_out_param->dim_size * sizeof(int));
        for (int j = 0; j < reshape_out_param->dim_size; ++j)
        {
            reshape_out_param->re_shape[j] = input->dims[j];
        }
    }

    return 0;
}

T
Thunder 已提交
843
static int reduce2avgpool(ir_graph_t* graph)
T
Thunder 已提交
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
{
    std::vector<ir_node_t*> reduce_mean_nodes;

    // get all softmax case.
    if (op_set < 13)
    {
        int node_num = graph->node_num;
        for (int i = 0; i < node_num; ++i)
        {
            ir_node_t* node = get_ir_graph_node(graph, i);
            if (node->op.type != OP_REDUCTION)
            {
                continue;
            }
            struct reduction_param* param = (struct reduction_param*)node->op.param_mem;

            if (param->type != 1 || param->dim_0 != 2 || param->dim_1 != 3 || param->dim_2 != -2 || param->dim_3 != -2)
            {
                continue;
            }

            reduce_mean_nodes.push_back(node);
        }
    }

    // support old spec onnx softmax.
    for (auto& node : reduce_mean_nodes)
    {
        if (change_node_op(node, OP_POOL) < 0)
        {
            return -1;
        }
        struct pool_param* pool_param = (struct pool_param*)node->op.param_mem;
        pool_param->global = 1;
        pool_param->pool_method = POOL_AVG;
    }

    return 0;
}

T
Thunder 已提交
884 885
int onnx_serializer::optimize_graph(ir_graph_t* graph)
{
T
Thunder 已提交
886
    set_log_level(LOG_EMERG);
T
Thunder 已提交
887
    if (infer_ir_graph_shape(graph) < 0)
T
Thunder 已提交
888 889 890 891
    {
        fprintf(stderr, "Skip internal optimize in onnx serializer.\n");
        return 0;
    }
T
Thunder 已提交
892 893
    if (deal_old_softmax(graph) < 0)
        return -1;
T
Thunder 已提交
894 895
    if (reduce2avgpool(graph) < 0)
        return -1;
T
Thunder 已提交
896
    fprintf(stderr, "Internal optimize in onnx serializer done.\n");
T
Thunder 已提交
897

T
Thunder 已提交
898 899 900
    return 0;
}

B
bzhang5 已提交
901
int onnx_serializer::load_model(ir_graph_t* graph, std::string model_file)
T
Thunder 已提交
902 903 904 905 906 907
{
    register_op_load();
    onnx::ModelProto model;
    if (load_model_file(model_file, model) < 0)
        return -1;
    const onnx::GraphProto& onnx_graph = model.graph();
908 909 910
    if (load_initializer_tensor(graph, onnx_graph) < 0)
        return -1;
    if (load_constant_tensor(graph, onnx_graph) < 0)
T
Thunder 已提交
911 912 913 914 915 916 917
        return -1;
    if (set_graph_input(graph, onnx_graph) < 0)
        return -1;
    if (load_graph_node(graph, onnx_graph) < 0)
        return -1;
    if (set_graph_output(graph, onnx_graph) < 0)
        return -1;
T
Thunder 已提交
918 919
    if (optimize_graph(graph) < 0)
        return -1;
T
Thunder 已提交
920 921 922 923

    graph->model_format = MODEL_FORMAT_ONNX;
    graph->graph_layout = TENGINE_LAYOUT_NCHW;
    graph->model_layout = TENGINE_LAYOUT_NCHW;
T
Thunder 已提交
924 925 926
    return 0;
}

B
bzhang5 已提交
927
graph_t onnx_serializer::onnx2tengine(std::string model_file)
T
Thunder 已提交
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
{
    fprintf(stderr, "----------onnx2tengine begin----------\n");

    context_t context = create_context(NULL, 1);
    ir_graph_t* ir_graph = create_ir_graph((struct context*)context);
    if (ir_graph == NULL)
    {
        destroy_context(context);
        return NULL;
    }
    ir_graph->attribute->private_context = 1; // new context

    int ret = load_model(ir_graph, model_file);
    if (0 != ret)
    {
        destroy_graph(ir_graph);
        return NULL;
    }
    ir_graph->device = find_default_device();

    fprintf(stderr, "----------onnx2tengine done.----------\n");
    return ir_graph;
}

T
Thunder 已提交
952
static int load_conv(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
953
{
N
nihui 已提交
954
    struct conv_param* conv_param = (struct conv_param*)node->op.param_mem;
T
Thunder 已提交
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
    for (int k = 0; k < onnx_node.attribute_size(); k++)
    {
        const onnx::AttributeProto& attr = onnx_node.attribute(k);

        if (attr.name() == "kernel_shape")
        {
            conv_param->kernel_h = attr.ints(0);
            conv_param->kernel_w = attr.ints(1);
        }
        else if (attr.name() == "strides")
        {
            conv_param->stride_h = attr.ints(0);
            conv_param->stride_w = attr.ints(1);
        }
        else if (attr.name() == "pads")
        {
            conv_param->pad_h0 = attr.ints(0);
            conv_param->pad_h1 = attr.ints(2);
            conv_param->pad_w0 = attr.ints(1);
            conv_param->pad_w1 = attr.ints(3);
        }
        else if (attr.name() == "group")
        {
            conv_param->group = attr.i();
        }
        else if (attr.name() == "dilations")
        {
            conv_param->dilation_h = attr.ints(0);
T
Thunder 已提交
983
            conv_param->dilation_w = attr.ints(1);
T
Thunder 已提交
984 985 986
        }
        else if (attr.name() == "auto_pad")
        {
T
Thunder 已提交
987 988 989 990 991 992
            /*
             * real pad will be calculated in infer shape.
             * flag:
             *      -1 : SAME_UPPER
             *      -2 : SAME_LOWER
             */
T
Thunder 已提交
993 994 995 996 997 998 999 1000
            const std::string& auto_pad = attr.s();

            if (auto_pad == "NOTSET")
            {
                continue;
            }
            else if (auto_pad == "SAME_UPPER")
            {
T
Thunder 已提交
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
                conv_param->pad_w0 = -1;
                conv_param->pad_w1 = -1;
                conv_param->pad_h0 = -1;
                conv_param->pad_h1 = -1;
            }
            else if (auto_pad == "SAME_LOWER")
            {
                conv_param->pad_w0 = -2;
                conv_param->pad_w1 = -2;
                conv_param->pad_h0 = -2;
                conv_param->pad_h1 = -2;
T
Thunder 已提交
1012
            }
T
Thunder 已提交
1013
            else if (auto_pad == "VALID")
T
Thunder 已提交
1014
            {
T
Thunder 已提交
1015 1016 1017 1018
                conv_param->pad_w0 = 0;
                conv_param->pad_w1 = 0;
                conv_param->pad_h0 = 0;
                conv_param->pad_h1 = 0;
T
Thunder 已提交
1019 1020
            }
            else
T
Thunder 已提交
1021
                fprintf(stderr, "%s attr.name: %s : %s not support.\n", node->name, attr.name().c_str(), auto_pad.c_str());
T
Thunder 已提交
1022 1023
        }
        else
T
Thunder 已提交
1024
            fprintf(stderr, "%s attr.name: %s \n", node->name, attr.name().c_str());
T
Thunder 已提交
1025 1026 1027 1028 1029 1030 1031 1032
    }

    struct tensor* weight = get_ir_graph_tensor(graph, node->input_tensors[1]);
    conv_param->output_channel = weight->dims[0]; /* onnx hide the output channel in weight .. */

    return 0;
}

T
Thunder 已提交
1033
static int load_relu(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1034
{
N
nihui 已提交
1035
    struct relu_param* relu_param = (struct relu_param*)node->op.param_mem;
T
Thunder 已提交
1036 1037 1038 1039
    relu_param->negative_slope = 0.f;
    return 0;
}

T
Thunder 已提交
1040
static int load_pool(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1041
{
N
nihui 已提交
1042
    struct pool_param* pool_param = (struct pool_param*)node->op.param_mem;
T
Thunder 已提交
1043 1044
    const std::string& onnx_op = onnx_node.op_type();

T
Thunder 已提交
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
    // set default param
    pool_param->pad_h0 = 0;
    pool_param->pad_h1 = 0;
    pool_param->pad_w0 = 0;
    pool_param->pad_w1 = 0;
    pool_param->stride_h = 1;
    pool_param->stride_w = 1;
    pool_param->global = 0;
    pool_param->caffe_flavor = 0;

N
nihui 已提交
1055
    if (onnx_op == "GlobalAveragePool")
T
Thunder 已提交
1056 1057 1058 1059
    {
        pool_param->global = 1;
        pool_param->pool_method = POOL_AVG;
    }
N
nihui 已提交
1060
    else if (onnx_op == "MaxPool" || onnx_op == "AveragePool")
T
Thunder 已提交
1061 1062 1063
    {
        pool_param->global = 0;

N
nihui 已提交
1064
        if (onnx_op == "AveragePool")
T
Thunder 已提交
1065 1066 1067 1068
            pool_param->pool_method = POOL_AVG;
        else
            pool_param->pool_method = POOL_MAX;

N
nihui 已提交
1069
        for (int k = 0; k < onnx_node.attribute_size(); k++)
T
Thunder 已提交
1070 1071 1072
        {
            const onnx::AttributeProto& attr = onnx_node.attribute(k);

N
nihui 已提交
1073
            if (attr.name() == "kernel_shape")
T
Thunder 已提交
1074 1075 1076 1077
            {
                pool_param->kernel_h = attr.ints(0);
                pool_param->kernel_w = attr.ints(1);
            }
N
nihui 已提交
1078
            else if (attr.name() == "strides")
T
Thunder 已提交
1079 1080 1081 1082
            {
                pool_param->stride_h = attr.ints(0);
                pool_param->stride_w = attr.ints(1);
            }
N
nihui 已提交
1083
            else if (attr.name() == "pads") /* onnx pads: x0_begin, x1_begin, ... , x0_end, x1_end, ... */
T
Thunder 已提交
1084 1085 1086 1087 1088
            {
                pool_param->pad_h0 = attr.ints(0);
                pool_param->pad_h1 = attr.ints(2);
                pool_param->pad_w0 = attr.ints(1);
                pool_param->pad_w1 = attr.ints(3);
T
Thunder 已提交
1089
                if (pool_param->pad_h0 != pool_param->pad_h1 && pool_param->pad_w0 != pool_param->pad_w1)
T
Thunder 已提交
1090
                {
T
Thunder 已提交
1091
                    pool_param->caffe_flavor = 1;
T
Thunder 已提交
1092
                }
T
Thunder 已提交
1093 1094 1095 1096 1097
            }
        }
    }
    else
    {
1098
        fprintf(stderr, "UNKNOWN POOLING: %s \n", onnx_op.c_str());
T
Thunder 已提交
1099 1100
        return -1;
    }
T
Thunder 已提交
1101 1102 1103 1104 1105 1106

    pool_param->pad_h0_org = pool_param->pad_h0;
    pool_param->pad_h1_org = pool_param->pad_h1;
    pool_param->pad_w0_org = pool_param->pad_w0;
    pool_param->pad_w1_org = pool_param->pad_w1;

T
Thunder 已提交
1107 1108 1109
    return 0;
}

T
Thunder 已提交
1110
static int load_flatten(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1111
{
N
nihui 已提交
1112
    struct flatten_param* flatten_param = (struct flatten_param*)node->op.param_mem;
T
Thunder 已提交
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
    flatten_param->axis = 1;

    if (1 == onnx_node.attribute_size())
    {
        const onnx::AttributeProto& attr = onnx_node.attribute(0);
        flatten_param->axis = attr.i();
    }
    return 0;
}

T
Thunder 已提交
1123
static int load_gemm(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1124
{
N
nihui 已提交
1125
    struct gemm_param* gemm_param = (struct gemm_param*)node->op.param_mem;
T
Thunder 已提交
1126
    // set default
1127 1128 1129 1130
    gemm_param->alpha = GetAttributeOrDefault<float>(onnx_node, "alpha", 1.0f);
    gemm_param->beta = GetAttributeOrDefault<float>(onnx_node, "beta", 1.0f);
    gemm_param->transA = GetAttributeOrDefault<int>(onnx_node, "transA", 0);
    gemm_param->transB = GetAttributeOrDefault<int>(onnx_node, "transB", 0);
T
Thunder 已提交
1131 1132 1133 1134 1135 1136

    ir_tensor_t* weight_tensor = get_ir_graph_tensor(graph, node->input_tensors[1]);
    ir_tensor_t* bias_tensor = get_ir_graph_tensor(graph, node->input_tensors[2]);

    if (gemm_param->transA)
    {
1137
        return -1;
T
Thunder 已提交
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
    }

    // create fc instead
    if (!gemm_param->transB)
    {
        // swap shape
        int k = weight_tensor->dims[0];
        int n = weight_tensor->dims[1];
        weight_tensor->dims[0] = n;
        weight_tensor->dims[1] = k;

T
Thunder 已提交
1149 1150
        // float* tmp = ( float* )sys_malloc(k * n * sizeof(float));
        std::vector<float> tmp(k * n);
N
nihui 已提交
1151
        float* data = (float*)weight_tensor->data;
T
Thunder 已提交
1152 1153 1154 1155 1156 1157
        for (int i = 0; i < n; i++)
            for (int j = 0; j < k; j++)
            {
                tmp[i * k + j] = data[j * n + i];
            }

T
Thunder 已提交
1158 1159
        memcpy(data, tmp.data(), n * k * sizeof(float));
        // sys_free(tmp);
T
Thunder 已提交
1160 1161 1162 1163
    }

    if (gemm_param->alpha != 1)
    {
N
nihui 已提交
1164
        float* data = (float*)weight_tensor->data;
T
Thunder 已提交
1165 1166 1167 1168 1169 1170 1171 1172
        int tensor_size = weight_tensor->dims[0] * weight_tensor->dims[1];

        for (int i = 0; i < tensor_size; i++)
            data[i] *= gemm_param->alpha;
    }

    if (gemm_param->beta != 1)
    {
N
nihui 已提交
1173
        float* data = (float*)bias_tensor->data;
T
Thunder 已提交
1174 1175 1176 1177 1178 1179 1180
        int tensor_size = weight_tensor->dims[0];

        for (int i = 0; i < tensor_size; i++)
            data[i] *= gemm_param->beta;
    }

    if (change_node_op(node, OP_FC) < 0)
T
Thunder 已提交
1181
    {
T
Thunder 已提交
1182
        return -1;
T
Thunder 已提交
1183
    }
T
Thunder 已提交
1184 1185
    struct fc_param* fc_param = (struct fc_param*)node->op.param_mem;
    fc_param->num_output = weight_tensor->dims[0];
N
nihui 已提交
1186

T
Thunder 已提交
1187 1188 1189
    return 0;
}

T
Thunder 已提交
1190
static int load_concat(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1191
{
N
nihui 已提交
1192
    struct concat_param* concat_param = (struct concat_param*)node->op.param_mem;
T
Thunder 已提交
1193

1194
    concat_param->axis = GetAttributeOrThrow<int>(onnx_node, "axis");
T
Thunder 已提交
1195 1196 1197 1198

    return 0;
}

T
Thunder 已提交
1199
static int load_bn(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1200
{
N
nihui 已提交
1201
    struct batchnorm_param* batchnorm_param = (struct batchnorm_param*)node->op.param_mem;
T
Thunder 已提交
1202

1203
    batchnorm_param->eps = GetAttributeOrThrow<float>(onnx_node, "epsilon");
T
Thunder 已提交
1204 1205 1206 1207

    return 0;
}

T
Thunder 已提交
1208
static int load_eltwise(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1209
{
N
nihui 已提交
1210
    struct eltwise_param* eltwise_param = (struct eltwise_param*)node->op.param_mem;
T
Thunder 已提交
1211 1212
    const std::string& op_name = onnx_node.op_type();
    if (op_name == "Add")
T
Thunder 已提交
1213
    {
N
nihui 已提交
1214
        eltwise_param->type = ELT_SUM;
T
Thunder 已提交
1215
    }
T
Thunder 已提交
1216
    else if (op_name == "Mul")
T
Thunder 已提交
1217
    {
N
nihui 已提交
1218
        eltwise_param->type = ELT_PROD;
T
Thunder 已提交
1219
    }
T
Thunder 已提交
1220
    else if (op_name == "Div")
T
Thunder 已提交
1221
    {
N
nihui 已提交
1222
        eltwise_param->type = ELT_DIV;
T
Thunder 已提交
1223
    }
T
Thunder 已提交
1224
    else if (op_name == "Floor")
T
Thunder 已提交
1225
    {
N
nihui 已提交
1226
        eltwise_param->type = ELT_FLOOR;
T
Thunder 已提交
1227
    }
T
Thunder 已提交
1228
    else if (op_name == "Exp")
T
Thunder 已提交
1229
    {
N
nihui 已提交
1230
        eltwise_param->type = ELT_EXP;
T
Thunder 已提交
1231
    }
T
Thunder 已提交
1232
    else if (op_name == "Sub")
T
Thunder 已提交
1233
    {
N
nihui 已提交
1234
        eltwise_param->type = ELT_SUB;
T
Thunder 已提交
1235
    }
T
Thunder 已提交
1236
    else if (op_name == "Pow")
T
Thunder 已提交
1237
    {
N
nihui 已提交
1238
        eltwise_param->type = ELT_POW;
T
Thunder 已提交
1239
    }
T
Thunder 已提交
1240
    else if (op_name == "Sqrt")
T
Thunder 已提交
1241
    {
N
nihui 已提交
1242
        eltwise_param->type = ELT_SQRT;
T
Thunder 已提交
1243
    }
T
Thunder 已提交
1244 1245 1246 1247

    return 0;
}

T
Thunder 已提交
1248
static int load_transpose(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1249
{
N
nihui 已提交
1250 1251
    struct transpose_param* transpose_param = (struct transpose_param*)node->op.param_mem;

T
Thunder 已提交
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
    const onnx::AttributeProto& attr = onnx_node.attribute(0);
    int size = attr.ints_size();
    transpose_param->tr_shape = (int*)sys_malloc(sizeof(int) * size);
    transpose_param->tr_shape_size = size;
    for (int i = 0; i < size; i++)
    {
        transpose_param->tr_shape[i] = attr.ints(i);
    }

    return 0;
}

T
Thunder 已提交
1264
static int load_clip(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1265
{
N
nihui 已提交
1266
    struct clip_param* clip_param = (struct clip_param*)node->op.param_mem;
T
Thunder 已提交
1267

1268
    if (node->input_num == 1)
T
Thunder 已提交
1269
    {
1270 1271
        clip_param->max = GetAttributeOrThrow<float>(onnx_node, "max");
        clip_param->min = GetAttributeOrThrow<float>(onnx_node, "min");
T
Thunder 已提交
1272
    }
1273
    else if (node->input_num == 3)
1274 1275 1276
    {
        ir_tensor_t* min = find_tensor(graph, onnx_node.input(1));
        ir_tensor_t* max = find_tensor(graph, onnx_node.input(2));
T
Thunder 已提交
1277 1278 1279 1280 1281 1282 1283 1284
        if (min->tensor_type == TENSOR_TYPE_CONST && max->tensor_type == TENSOR_TYPE_CONST)
        {
            float* min_data = (float*)min->data;
            float* max_data = (float*)max->data;
            clip_param->min = min_data[0];
            clip_param->max = max_data[0];
            node->input_num = 1;
        }
1285
    }
1286 1287 1288 1289
    else
    {
        throw std::invalid_argument("unsupported clip op input num: " + std::to_string(node->input_num));
    }
T
Thunder 已提交
1290 1291 1292 1293

    return 0;
}

T
Thunder 已提交
1294
static int load_reshape(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1295
{
N
nihui 已提交
1296
    struct reshape_param* reshape_param = (struct reshape_param*)node->op.param_mem;
T
Thunder 已提交
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307

    ir_tensor_t* shape_tensor = find_tensor(graph, onnx_node.input(1));
    if (shape_tensor == nullptr)
    {
        fprintf(stderr, "find shape tensor of reshape node failed.\n");
        return -1;
    }
    reshape_param->is_onnx = 1;
    int size = shape_tensor->elem_num;
    reshape_param->re_shape = (int*)sys_malloc(sizeof(int) * size);
    reshape_param->dim_size = size;
B
bzhang5 已提交
1308

T
Thunder 已提交
1309 1310
    int64_t* data = (int64_t*)shape_tensor->data;
    for (int i = 0; i < size; i++)
N
nihui 已提交
1311
    {
T
Thunder 已提交
1312 1313 1314 1315 1316
        reshape_param->re_shape[i] = data[i];
    }
    return 0;
}

T
Thunder 已提交
1317
static int load_no_param(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1318 1319 1320 1321 1322
{
    // no param
    return 0;
}

T
Thunder 已提交
1323
static int load_softmax(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1324
{
N
nihui 已提交
1325
    struct softmax_param* softmax_param = (struct softmax_param*)node->op.param_mem;
T
Thunder 已提交
1326
    softmax_param->axis = 1; // default
T
Thunder 已提交
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339

    for (int k = 0; k < onnx_node.attribute_size(); k++)
    {
        const onnx::AttributeProto& attr = onnx_node.attribute(k);
        if (attr.name() == "axis")
        {
            softmax_param->axis = attr.i();
        }
    }

    return 0;
}

T
Thunder 已提交
1340
static int load_elu(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1341
{
N
nihui 已提交
1342
    struct elu_param* elu_param = (struct elu_param*)node->op.param_mem;
1343
    elu_param->alpha = GetAttributeOrDefault<float>(onnx_node, "alpha", 1.f);
T
Thunder 已提交
1344 1345 1346 1347

    return 0;
}

T
Thunder 已提交
1348
static int load_interp(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1349
{
1350
    std::string mode = GetAttributeOrDefault<std::string>(onnx_node, "mode", "nearest");
N
nihui 已提交
1351
    if (mode != "nearest")
T
Thunder 已提交
1352
    {
N
nihui 已提交
1353
        struct interp_param* interp_param = (struct interp_param*)node->op.param_mem;
T
Thunder 已提交
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382

        if (onnx_node.input_size() == 1)
        {
            for (int k = 0; k < onnx_node.attribute_size(); k++)
            {
                const onnx::AttributeProto& attr = onnx_node.attribute(k);
                if (attr.name() == "scales")
                {
                    if (attr.floats_size() == 4)
                    {
                        float num0 = attr.floats(0);
                        float num1 = attr.floats(1);
                        float num2 = attr.floats(2);
                        float num3 = attr.floats(3);
                        interp_param->height_scale = num2 / num0;
                        interp_param->width_scale = num3 / num1;
                    }
                    else
                    {
                        interp_param->height_scale = attr.f();
                        interp_param->width_scale = attr.f();
                    }
                }
            }
        }
        else
        {
            const std::string& input_name = onnx_node.input(1);
            ir_tensor_t* tensor = find_tensor(graph, input_name);
N
nihui 已提交
1383
            float* data = (float*)tensor->data;
T
Thunder 已提交
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395

            interp_param->height_scale = data[2];
            interp_param->width_scale = data[3];
        }
        if (mode == "nearest")
        {
            interp_param->resize_type = 1;
        }
        else if (mode == "bilinear" || mode == "linear")
        {
            interp_param->resize_type = 2;
        }
N
nihui 已提交
1396
    }
T
Thunder 已提交
1397 1398
    else
    {
T
Thunder 已提交
1399
        if (change_node_op(node, OP_RESIZE) < 0)
T
Thunder 已提交
1400 1401 1402 1403 1404 1405 1406 1407 1408
        {
            return -1;
        }
        struct resize_param* resize_param = (struct resize_param*)node->op.param_mem;

        if (onnx_node.input_size() == 2)
        {
            const std::string& input_name = onnx_node.input(1);
            ir_tensor_t* tensor = find_tensor(graph, input_name);
N
nihui 已提交
1409
            float* data = (float*)tensor->data;
T
Thunder 已提交
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
            resize_param->scale_h = data[2];
            resize_param->scale_w = data[3];
        }
        else
        {
            resize_param->scale_w = 1.f;
            resize_param->scale_h = 1.f;
        }
    }

    return 0;
}

T
Thunder 已提交
1423
static int load_leaky_relu(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1424
{
N
nihui 已提交
1425
    struct relu_param* relu_param = (struct relu_param*)node->op.param_mem;
T
Thunder 已提交
1426 1427 1428 1429 1430 1431
    const onnx::AttributeProto& attr = onnx_node.attribute(0);
    relu_param->negative_slope = attr.f();

    return 0;
}

T
Thunder 已提交
1432
static int load_slice(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1433
{
N
nihui 已提交
1434
    struct slice_param* slice_param = (struct slice_param*)node->op.param_mem;
T
Thunder 已提交
1435 1436 1437 1438 1439

    slice_param->step = 1;
    slice_param->axis = 0;
    slice_param->begin = 0;
    slice_param->end = -1;
T
Thunder 已提交
1440 1441 1442 1443
    slice_param->slice_point_ = nullptr;
    slice_param->begin_ = nullptr;
    slice_param->size_ = nullptr;

T
Thunder 已提交
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
    if (onnx_node.input_size() == 1)
    {
        for (int k = 0; k < onnx_node.attribute_size(); k++)
        {
            const onnx::AttributeProto& attr = onnx_node.attribute(k);
            if (attr.name() == "axes")
            {
                slice_param->axis = attr.ints(0);
            }
            else if (attr.name() == "ends")
            {
                long long end = attr.ints(0);
                if (end > INT_MAX)
T
Thunder 已提交
1457
                {
T
Thunder 已提交
1458
                    end = INT_MAX;
T
Thunder 已提交
1459
                }
N
nihui 已提交
1460
                slice_param->end = (int)end;
T
Thunder 已提交
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
            }
            else if (attr.name() == "starts")
            {
                slice_param->begin = attr.ints(0);
            }
        }
    }
    else
    {
        ir_tensor_t* node_tensor = nullptr;
        node_tensor = find_tensor(graph, onnx_node.input(1));
        slice_param->begin = (int)(*(int64_t*)(node_tensor->data));

        node_tensor = find_tensor(graph, onnx_node.input(2));
        slice_param->end = (int)(*(int64_t*)(node_tensor->data));

        if (onnx_node.input_size() >= 4)
        {
            node_tensor = find_tensor(graph, onnx_node.input(3));
            slice_param->axis = (int)(*(int64_t*)(node_tensor->data));
        }

        if (onnx_node.input_size() >= 5)
        {
            node_tensor = find_tensor(graph, onnx_node.input(4));
            slice_param->step = (int)(*(int64_t*)(node_tensor->data));
        }
    }

    slice_param->iscaffe = 0;
    slice_param->ismxnet = 0;
    slice_param->isonnx = 1;
    return 0;
}

T
Thunder 已提交
1496
static int load_split(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1497
{
N
nihui 已提交
1498
    struct split_param* split_param = (struct split_param*)node->op.param_mem;
T
Thunder 已提交
1499
    split_param->is_onnx = true;
1500
    split_param->axis = GetAttributeOrDefault<int>(onnx_node, "axis", 0);
T
Thunder 已提交
1501 1502 1503
    for (int k = 0; k < onnx_node.attribute_size(); k++)
    {
        const onnx::AttributeProto& attr = onnx_node.attribute(k);
1504
        if (attr.name() == "split")
T
Thunder 已提交
1505 1506
        {
            int size = attr.ints_size();
1507
            struct vector* new_shape = create_vector(sizeof(int), NULL);
T
Thunder 已提交
1508 1509 1510 1511
            split_param->split_dim = size;
            for (int i = 0; i < size; i++)
            {
                int tmp = attr.ints(i);
1512
                push_vector_data(new_shape, &tmp);
T
Thunder 已提交
1513
            }
1514
            split_param->split_sizes_ = new_shape;
T
Thunder 已提交
1515 1516 1517 1518 1519 1520 1521
        }
    }
    split_param->is_caffe = false;

    return 0;
}

T
Thunder 已提交
1522
static int load_unsqueeze(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1523
{
N
nihui 已提交
1524
    struct unsqueeze_param* unsqueeze_param = (struct unsqueeze_param*)node->op.param_mem;
T
Thunder 已提交
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538

    std::vector<int> axises;
    for (int k = 0; k < onnx_node.attribute_size(); k++)
    {
        const onnx::AttributeProto& attr = onnx_node.attribute(k);
        if (attr.name() == "axes")
        {
            for (int i = 0; i < attr.ints_size(); i++)
            {
                axises.push_back(attr.ints(i));
            }
        }
    }

T
Thunder 已提交
1539 1540 1541 1542
    /* opset 13 */
    if (axises.empty() && node->input_num == 2)
    {
        ir_tensor_t* axes_tensor = get_ir_graph_tensor(graph, node->input_tensors[1]);
N
nihui 已提交
1543
        int* data = (int*)axes_tensor->data;
T
Thunder 已提交
1544 1545 1546 1547
        for (int i = 0; i < axes_tensor->elem_num; i++)
        {
            axises.push_back(data[i]);
        }
N
nihui 已提交
1548

T
Thunder 已提交
1549 1550 1551 1552 1553
        // remove axes tensor
        node->input_num = 1;
    }

    sort(axises.begin(), axises.end());
T
Thunder 已提交
1554 1555 1556 1557 1558 1559
    unsqueeze_param->axises_size = axises.size();
    unsqueeze_param->axises = (int*)sys_malloc(sizeof(int) * unsqueeze_param->axises_size);
    for (size_t i = 0; i < axises.size(); i++)
    {
        unsqueeze_param->axises[i] = axises[i];
    }
N
nihui 已提交
1560

T
Thunder 已提交
1561 1562 1563
    return 0;
}

T
Thunder 已提交
1564
static int load_squeeze(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1565
{
N
nihui 已提交
1566
    struct squeeze_param* squeeze_param = (struct squeeze_param*)node->op.param_mem;
T
Thunder 已提交
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593

    for (int k = 0; k < onnx_node.attribute_size(); k++)
    {
        const onnx::AttributeProto& attr = onnx_node.attribute(k);
        if (attr.name() == "axes")
        {
            for (int i = 0; i < attr.ints_size(); i++)
            {
                if (0 == attr.ints(i))
                {
                    squeeze_param->dim_0 = 1;
                }
                else if (1 == attr.ints(i))
                {
                    squeeze_param->dim_1 = 1;
                }
                else if (2 == attr.ints(i))
                {
                    squeeze_param->dim_2 = 1;
                }
                else if (3 == attr.ints(i))
                {
                    squeeze_param->dim_3 = 1;
                }
            }
        }
    }
N
nihui 已提交
1594

T
Thunder 已提交
1595 1596 1597
    return 0;
}

T
Thunder 已提交
1598
static int load_matmul(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1599 1600 1601 1602
{
    ir_tensor_t* input_tensor = find_tensor(graph, onnx_node.input(0));
    ir_tensor_t* weight_tensor = find_tensor(graph, onnx_node.input(1));

N
nihui 已提交
1603
    if (2 == input_tensor->dim_num && weight_tensor->tensor_type == TENSOR_TYPE_CONST)
T
Thunder 已提交
1604 1605 1606 1607 1608 1609 1610 1611
    {
        // swap shape
        int k = weight_tensor->dims[0];
        int n = weight_tensor->dims[1];

        weight_tensor->dims[0] = n;
        weight_tensor->dims[1] = k;

T
Thunder 已提交
1612 1613
        // float* tmp = ( float* )sys_malloc(k * n * sizeof(float));
        std::vector<float> tmp(k * n);
N
nihui 已提交
1614
        float* data = (float*)weight_tensor->data;
T
Thunder 已提交
1615 1616 1617 1618 1619 1620 1621 1622

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < k; j++)
            {
                tmp[i * k + j] = data[j * n + i];
            }
        }
T
Thunder 已提交
1623 1624
        memcpy(data, tmp.data(), n * k * sizeof(float));
        // free(tmp);
T
Thunder 已提交
1625 1626

        if (change_node_op(node, OP_FC) < 0)
T
Thunder 已提交
1627
        {
T
Thunder 已提交
1628
            return -1;
T
Thunder 已提交
1629
        }
N
nihui 已提交
1630
        struct fc_param* fc_param = (struct fc_param*)node->op.param_mem;
T
Thunder 已提交
1631 1632
        fc_param->num_output = weight_tensor->dims[0];
    }
N
nihui 已提交
1633

T
Thunder 已提交
1634 1635 1636
    return 0;
}

T
Thunder 已提交
1637
static int load_reducel2(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1638
{
N
nihui 已提交
1639
    struct reducel2_param* reducel2_param = (struct reducel2_param*)node->op.param_mem;
1640 1641 1642 1643
    const auto axes = GetAttributeOrThrow<std::vector<int> >(onnx_node, "axes");
    TASSERT(axes.size() == 1);
    reducel2_param->axis = axes[0];
    reducel2_param->keepdim = GetAttributeOrDefault<int>(onnx_node, "keepdims", 1);
N
nihui 已提交
1644

T
Thunder 已提交
1645 1646 1647
    return 0;
}

T
Thunder 已提交
1648
static int load_gather(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1649
{
N
nihui 已提交
1650
    struct gather_param* gather_param = (struct gather_param*)node->op.param_mem;
T
Thunder 已提交
1651

1652
    gather_param->axis = GetAttributeOrDefault<int>(onnx_node, "axis", 0);
T
Thunder 已提交
1653
    ir_tensor_t* indices_tensor = find_tensor(graph, onnx_node.input(1));
N
nihui 已提交
1654
    int64_t* data = (int64_t*)indices_tensor->data;
T
Thunder 已提交
1655 1656
    gather_param->indices_num = *data;
    gather_param->is_onnx = 1;
N
nihui 已提交
1657

T
Thunder 已提交
1658 1659 1660
    return 0;
}

T
Thunder 已提交
1661
static int load_comparison(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1662
{
N
nihui 已提交
1663
    struct comparison_param* comparison_param = (struct comparison_param*)node->op.param_mem;
T
Thunder 已提交
1664 1665 1666
    const std::string& op_name = onnx_node.op_type();

    if (op_name == "Greater")
T
Thunder 已提交
1667
    {
T
Thunder 已提交
1668
        comparison_param->type = COMP_GREATER;
T
Thunder 已提交
1669
    }
T
Thunder 已提交
1670
    else if (op_name == "Equal")
T
Thunder 已提交
1671
    {
T
Thunder 已提交
1672
        comparison_param->type = COMP_EQUAL;
T
Thunder 已提交
1673
    }
T
Thunder 已提交
1674
    else if (op_name == "Less")
T
Thunder 已提交
1675
    {
T
Thunder 已提交
1676
        comparison_param->type = COMP_LESS;
T
Thunder 已提交
1677
    }
T
Thunder 已提交
1678 1679 1680 1681

    return 0;
}

T
Thunder 已提交
1682
static int load_LRN(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1683
{
N
nihui 已提交
1684
    struct lrn_param* lrn_param = (struct lrn_param*)node->op.param_mem;
1685 1686 1687 1688
    lrn_param->alpha = GetAttributeOrDefault<float>(onnx_node, "alpha", 0.0001);
    lrn_param->beta = GetAttributeOrDefault<float>(onnx_node, "alpha", 0.0001);
    lrn_param->k = GetAttributeOrDefault<float>(onnx_node, "bias", 1.);
    lrn_param->local_size = GetAttributeOrThrow<int>(onnx_node, "size");
N
nihui 已提交
1689

T
Thunder 已提交
1690 1691 1692
    return 0;
}

T
Thunder 已提交
1693
static int load_unary(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1694
{
N
nihui 已提交
1695
    struct unary_param* unary_param = (struct unary_param*)node->op.param_mem;
T
Thunder 已提交
1696 1697 1698
    const std::string& op_name = onnx_node.op_type();

    if (op_name == "Abs")
T
Thunder 已提交
1699
    {
T
Thunder 已提交
1700
        unary_param->type = 0;
T
Thunder 已提交
1701
    }
T
Thunder 已提交
1702
    else if (op_name == "Neg")
T
Thunder 已提交
1703
    {
T
Thunder 已提交
1704
        unary_param->type = 1;
T
Thunder 已提交
1705
    }
T
Thunder 已提交
1706
    else if (op_name == "Ceil")
T
Thunder 已提交
1707
    {
T
Thunder 已提交
1708
        unary_param->type = 3;
T
Thunder 已提交
1709
    }
T
Thunder 已提交
1710
    else if (op_name == "Log")
T
Thunder 已提交
1711
    {
T
Thunder 已提交
1712
        unary_param->type = 8;
T
Thunder 已提交
1713
    }
T
Thunder 已提交
1714
    else if (op_name == "Cos")
T
Thunder 已提交
1715
    {
T
Thunder 已提交
1716
        unary_param->type = 10;
T
Thunder 已提交
1717
    }
T
Thunder 已提交
1718
    else if (op_name == "Asin")
T
Thunder 已提交
1719
    {
T
Thunder 已提交
1720
        unary_param->type = 12;
T
Thunder 已提交
1721
    }
T
Thunder 已提交
1722
    else if (op_name == "Acos")
T
Thunder 已提交
1723
    {
T
Thunder 已提交
1724
        unary_param->type = 13;
T
Thunder 已提交
1725
    }
T
Thunder 已提交
1726
    else if (op_name == "Atan")
T
Thunder 已提交
1727
    {
T
Thunder 已提交
1728
        unary_param->type = 14;
T
Thunder 已提交
1729
    }
N
nihui 已提交
1730

T
Thunder 已提交
1731 1732 1733
    return 0;
}

T
Thunder 已提交
1734
static int load_logical(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1735
{
N
nihui 已提交
1736
    struct logical_param* logical_param = (struct logical_param*)node->op.param_mem;
T
Thunder 已提交
1737 1738 1739
    const std::string& op_name = onnx_node.op_type();

    if (op_name == "And")
T
Thunder 已提交
1740
    {
T
Thunder 已提交
1741
        logical_param->type = 0;
T
Thunder 已提交
1742
    }
T
Thunder 已提交
1743
    else if (op_name == "Or")
T
Thunder 已提交
1744
    {
T
Thunder 已提交
1745
        logical_param->type = 1;
T
Thunder 已提交
1746
    }
N
nihui 已提交
1747

T
Thunder 已提交
1748 1749 1750
    return 0;
}

T
Thunder 已提交
1751
static int load_pad(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1752
{
N
nihui 已提交
1753 1754 1755
    struct pad_param* pad_param = (struct pad_param*)node->op.param_mem;

    if (onnx_node.attribute_size() == 1) // since opset 11, 'pads' and 'value' have been moved from attributes to inputs
T
Thunder 已提交
1756
    {
T
Thunder 已提交
1757 1758
        const std::string& input_name_pad = onnx_node.input(1);
        ir_tensor_t* tensor_pad = find_tensor(graph, input_name_pad);
N
nihui 已提交
1759
        int64_t* data_pad = (int64_t*)tensor_pad->data;
T
Thunder 已提交
1760 1761 1762 1763 1764 1765 1766 1767 1768
        pad_param->pad_0_h = data_pad[0];
        pad_param->pad_0_w = data_pad[4];
        pad_param->pad_1_h = data_pad[1];
        pad_param->pad_1_w = data_pad[5];
        pad_param->pad_2_h = data_pad[2];
        pad_param->pad_2_w = data_pad[6];
        pad_param->pad_3_h = data_pad[3];
        pad_param->pad_3_w = data_pad[7];

B
bzhang5 已提交
1769 1770 1771 1772
        if (onnx_node.input_size() > 2)
        {
            const std::string& input_name_value = onnx_node.input(2);
            ir_tensor_t* tensor_value = find_tensor(graph, input_name_value);
N
nihui 已提交
1773
            float* data_value = (float*)tensor_value->data;
B
bzhang5 已提交
1774 1775
            pad_param->value = data_value[0];
        }
T
Thunder 已提交
1776
    }
N
nihui 已提交
1777

T
Thunder 已提交
1778 1779 1780 1781 1782 1783 1784 1785 1786
    for (int k = 0; k < onnx_node.attribute_size(); k++)
    {
        const onnx::AttributeProto& attr = onnx_node.attribute(k);
        if (attr.name() == "mode")
        {
            if (attr.s() == "constant")
            {
                pad_param->mode = 0;
            }
1787
            else if (attr.s() == "edge")
T
Thunder 已提交
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
            {
                pad_param->mode = 1;
            }
            else
            {
                pad_param->mode = 2;
            }
        }
        if (attr.name() == "pads")
        {
            pad_param->pad_0_h = attr.ints(0);
            pad_param->pad_0_w = attr.ints(4);
            pad_param->pad_1_h = attr.ints(1);
            pad_param->pad_1_w = attr.ints(5);
            pad_param->pad_2_h = attr.ints(2);
            pad_param->pad_2_w = attr.ints(6);
            pad_param->pad_3_h = attr.ints(3);
            pad_param->pad_3_w = attr.ints(7);
        }
        if (attr.name() == "value")
        {
            pad_param->value = attr.f();
        }
    }
1812

T
Thunder 已提交
1813 1814 1815
    return 0;
}

T
Thunder 已提交
1816
static int load_reduce(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1817
{
N
nihui 已提交
1818
    struct reduction_param* reduction_param = (struct reduction_param*)node->op.param_mem;
T
Thunder 已提交
1819 1820 1821
    const std::string& op_name = onnx_node.op_type();

    if (op_name == "ReduceSum")
T
Thunder 已提交
1822
    {
T
Thunder 已提交
1823
        reduction_param->type = 0;
T
Thunder 已提交
1824
    }
T
Thunder 已提交
1825
    else if (op_name == "ReduceMean")
T
Thunder 已提交
1826
    {
T
Thunder 已提交
1827
        reduction_param->type = 1;
T
Thunder 已提交
1828
    }
T
Thunder 已提交
1829
    else if (op_name == "ReduceSumSquare")
T
Thunder 已提交
1830
    {
T
Thunder 已提交
1831
        reduction_param->type = 3;
T
Thunder 已提交
1832
    }
T
Thunder 已提交
1833
    else if (op_name == "ReduceMax")
T
Thunder 已提交
1834
    {
T
Thunder 已提交
1835
        reduction_param->type = 4;
T
Thunder 已提交
1836
    }
T
Thunder 已提交
1837
    else if (op_name == "ReduceMin")
T
Thunder 已提交
1838
    {
T
Thunder 已提交
1839
        reduction_param->type = 5;
T
Thunder 已提交
1840
    }
T
Thunder 已提交
1841
    else if (op_name == "ReduceProd")
T
Thunder 已提交
1842
    {
T
Thunder 已提交
1843
        reduction_param->type = 6;
T
Thunder 已提交
1844
    }
T
Thunder 已提交
1845
    else if (op_name == "ReduceLogSum")
T
Thunder 已提交
1846
    {
T
Thunder 已提交
1847
        reduction_param->type = 9;
T
Thunder 已提交
1848
    }
T
Thunder 已提交
1849
    else if (op_name == "ReduceLogSumExp")
T
Thunder 已提交
1850
    {
T
Thunder 已提交
1851
        reduction_param->type = 10;
T
Thunder 已提交
1852
    }
T
Thunder 已提交
1853 1854 1855 1856 1857 1858

    reduction_param->dim_0 = -2;
    reduction_param->dim_1 = -2;
    reduction_param->dim_2 = -2;
    reduction_param->dim_3 = -2;
    reduction_param->keepdim = 1;
N
nihui 已提交
1859

T
Thunder 已提交
1860 1861
    ir_tensor_t* input_tensor = get_ir_graph_tensor(graph, node->input_tensors[0]);
    int input_dim_num = input_tensor->dim_num;
T
Thunder 已提交
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
    int size = onnx_node.attribute_size();
    for (int i = 0; i < size; i++)
    {
        const onnx::AttributeProto& attr = onnx_node.attribute(i);
        if (attr.name() == "keepdims")
        {
            reduction_param->keepdim = attr.i();
        }
        else if (attr.name() == "axes")
        {
            int axis_size = attr.ints_size();
            if (axis_size == 1)
            {
                int attr_0 = attr.ints(0);
                if (attr.ints(0) < 0)
T
Thunder 已提交
1877 1878 1879
                {
                    attr_0 = input_dim_num + attr.ints(0);
                }
T
Thunder 已提交
1880 1881 1882 1883 1884 1885 1886
                reduction_param->dim_0 = attr_0;
            }
            else if (axis_size == 2)
            {
                int attr_0 = attr.ints(0);
                int attr_1 = attr.ints(1);
                if (attr.ints(0) < 0)
T
Thunder 已提交
1887 1888 1889
                {
                    attr_0 = input_dim_num + attr.ints(0);
                }
T
Thunder 已提交
1890
                if (attr.ints(1) < 0)
T
Thunder 已提交
1891 1892 1893
                {
                    attr_0 = input_dim_num + attr.ints(1);
                }
T
Thunder 已提交
1894 1895 1896 1897 1898 1899 1900 1901 1902
                reduction_param->dim_0 = attr_0;
                reduction_param->dim_1 = attr_1;
            }
            else if (axis_size == 3)
            {
                int attr_0 = attr.ints(0);
                int attr_1 = attr.ints(1);
                int attr_2 = attr.ints(2);
                if (attr.ints(0) < 0)
T
Thunder 已提交
1903 1904 1905
                {
                    attr_0 = input_dim_num + attr.ints(0);
                }
T
Thunder 已提交
1906
                if (attr.ints(1) < 0)
T
Thunder 已提交
1907 1908 1909
                {
                    attr_0 = input_dim_num + attr.ints(1);
                }
T
Thunder 已提交
1910
                if (attr.ints(2) < 0)
T
Thunder 已提交
1911 1912 1913
                {
                    attr_0 = input_dim_num + attr.ints(2);
                }
T
Thunder 已提交
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
                reduction_param->dim_0 = attr_0;
                reduction_param->dim_1 = attr_1;
                reduction_param->dim_2 = attr_2;
            }
            else if (axis_size == 4)
            {
                int attr_0 = attr.ints(0);
                int attr_1 = attr.ints(1);
                int attr_2 = attr.ints(2);
                int attr_3 = attr.ints(3);
                if (attr.ints(0) < 0)
T
Thunder 已提交
1925 1926 1927
                {
                    attr_0 = input_dim_num + attr.ints(0);
                }
T
Thunder 已提交
1928
                if (attr.ints(1) < 0)
T
Thunder 已提交
1929 1930 1931
                {
                    attr_0 = input_dim_num + attr.ints(1);
                }
T
Thunder 已提交
1932
                if (attr.ints(2) < 0)
T
Thunder 已提交
1933 1934 1935
                {
                    attr_0 = input_dim_num + attr.ints(2);
                }
T
Thunder 已提交
1936
                if (attr.ints(3) < 0)
T
Thunder 已提交
1937 1938 1939
                {
                    attr_0 = input_dim_num + attr.ints(3);
                }
T
Thunder 已提交
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949
                reduction_param->dim_0 = attr_0;
                reduction_param->dim_1 = attr_1;
                reduction_param->dim_2 = attr_2;
                reduction_param->dim_3 = attr_3;
            }
        }
    }
    return 0;
}

T
Thunder 已提交
1950
static int load_argmax(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1951
{
N
nihui 已提交
1952 1953
    struct argmax_param* argmax_param = (struct argmax_param*)node->op.param_mem;

1954
    argmax_param->axis = GetAttributeOrDefault<int>(onnx_node, "axis", 0);
F
FeiGeChuanShu 已提交
1955
    argmax_param->keepdims = GetAttributeOrDefault<int>(onnx_node, "keepdims", 1);
N
nihui 已提交
1956

T
Thunder 已提交
1957 1958 1959
    return 0;
}

T
Thunder 已提交
1960
static int load_argmin(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1961
{
N
nihui 已提交
1962 1963
    struct argmin_param* argmin_param = (struct argmin_param*)node->op.param_mem;

1964
    argmin_param->axis = GetAttributeOrDefault<int>(onnx_node, "axis", 0);
F
FeiGeChuanShu 已提交
1965
    argmin_param->keepdims = GetAttributeOrDefault<int>(onnx_node, "keepdims", 1);
N
nihui 已提交
1966

T
Thunder 已提交
1967 1968 1969
    return 0;
}

T
Thunder 已提交
1970
static int load_log_softmax(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1971
{
N
nihui 已提交
1972 1973
    struct logsoftmax_param* logsoftmax_param = (struct logsoftmax_param*)node->op.param_mem;

1974
    logsoftmax_param->axis = GetAttributeOrDefault<int>(onnx_node, "axis", -1);
N
nihui 已提交
1975

T
Thunder 已提交
1976 1977 1978
    return 0;
}

T
Thunder 已提交
1979
static int load_deconv(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
1980
{
N
nihui 已提交
1981 1982
    struct deconv_param* deconv_param = (struct deconv_param*)node->op.param_mem;

T
Thunder 已提交
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
    for (int k = 0; k < onnx_node.attribute_size(); k++)
    {
        const onnx::AttributeProto& attr = onnx_node.attribute(k);
        if (attr.name() == "kernel_shape")
        {
            deconv_param->kernel_h = attr.ints(0);
            deconv_param->kernel_w = attr.ints(1);
        }
        else if (attr.name() == "strides")
        {
            deconv_param->stride_h = attr.ints(0);
            deconv_param->stride_w = attr.ints(1);
        }
        else if (attr.name() == "output_padding")
        {
            deconv_param->output_pad_h0 = attr.ints(0);
            deconv_param->output_pad_w0 = attr.ints(1);
        }
        else if (attr.name() == "pads")
        {
            deconv_param->pad_h0 = attr.ints(0);
            deconv_param->pad_h1 = attr.ints(2);
            deconv_param->pad_w0 = attr.ints(1);
            deconv_param->pad_w1 = attr.ints(3);
        }
        else if (attr.name() == "group")
        {
            deconv_param->group = attr.i();
        }
        else if (attr.name() == "dilations")
        {
            deconv_param->dilation_h = attr.ints(0);
T
Thunder 已提交
2015
            deconv_param->dilation_w = attr.ints(1);
T
Thunder 已提交
2016 2017
        }
        else
T
Thunder 已提交
2018
            fprintf(stderr, "attr.name: %s \n", attr.name().c_str());
T
Thunder 已提交
2019 2020 2021 2022 2023 2024 2025
    }

    /* update the input tensor data layout */
    for (int k = 0; k < onnx_node.input_size(); k++)
    {
        const std::string& input_name = onnx_node.input(k);
        ir_tensor_t* tensor = find_tensor(graph, input_name);
N
nihui 已提交
2026
        if (k == 1) // weight
T
Thunder 已提交
2027 2028 2029
        {
            int* dim = tensor->dims;
            /* onnx hide the output channel in weight ..*/
S
shitouren1994 已提交
2030 2031
            /* The number of channels in the output should be equal to W.shape[1] * group */
            deconv_param->num_output = dim[1] * deconv_param->group;
T
Thunder 已提交
2032 2033 2034 2035
            deconv_param->kernel_h = dim[2];
            deconv_param->kernel_w = dim[3];
        }
    }
N
nihui 已提交
2036

T
Thunder 已提交
2037 2038 2039
    return 0;
}

T
Thunder 已提交
2040
static int load_scatter(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
2041
{
N
nihui 已提交
2042 2043
    struct scatter_param* scatter_param = (struct scatter_param*)node->op.param_mem;

T
Thunder 已提交
2044 2045 2046 2047 2048 2049 2050
    int size = onnx_node.attribute_size();
    scatter_param->axis = 0;
    scatter_param->is_onnx = 1;
    for (int i = 0; i < size; i++)
    {
        const onnx::AttributeProto& attr = onnx_node.attribute(i);
        if (attr.name() == "axis")
T
Thunder 已提交
2051
        {
T
Thunder 已提交
2052
            scatter_param->axis = attr.i();
T
Thunder 已提交
2053
        }
T
Thunder 已提交
2054
    }
N
nihui 已提交
2055

T
Thunder 已提交
2056 2057 2058
    return 0;
}

T
Thunder 已提交
2059
static int load_selu(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
2060
{
N
nihui 已提交
2061 2062
    struct selu_param* selu_param = (struct selu_param*)node->op.param_mem;

T
Thunder 已提交
2063 2064 2065 2066
    for (int k = 0; k < onnx_node.attribute_size(); k++)
    {
        const onnx::AttributeProto& attr = onnx_node.attribute(k);
        if (attr.name() == "alpha")
T
Thunder 已提交
2067
        {
T
Thunder 已提交
2068
            selu_param->alpha = attr.f();
T
Thunder 已提交
2069
        }
T
Thunder 已提交
2070
        else if (attr.name() == "gamma")
T
Thunder 已提交
2071
        {
T
Thunder 已提交
2072
            selu_param->lambda = attr.f();
T
Thunder 已提交
2073
        }
T
Thunder 已提交
2074
    }
N
nihui 已提交
2075

T
Thunder 已提交
2076 2077 2078
    return 0;
}

T
Thunder 已提交
2079
static int load_hard_sigmoid(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
2080
{
N
nihui 已提交
2081
    struct hard_sigmoid_param* hard_sigmoid_param = (struct hard_sigmoid_param*)node->op.param_mem;
2082 2083
    hard_sigmoid_param->alpha = 1 / 6.f;
    hard_sigmoid_param->beta = 0.5f;
T
Thunder 已提交
2084 2085 2086 2087
    for (int k = 0; k < onnx_node.attribute_size(); k++)
    {
        const onnx::AttributeProto& attr = onnx_node.attribute(k);
        if (attr.name() == "alpha")
T
Thunder 已提交
2088
        {
T
Thunder 已提交
2089
            hard_sigmoid_param->alpha = attr.f();
T
Thunder 已提交
2090
        }
T
Thunder 已提交
2091
        else if (attr.name() == "beta")
T
Thunder 已提交
2092
        {
T
Thunder 已提交
2093
            hard_sigmoid_param->beta = attr.f();
T
Thunder 已提交
2094
        }
T
Thunder 已提交
2095
    }
N
nihui 已提交
2096

T
Thunder 已提交
2097 2098 2099
    return 0;
}

T
Thunder 已提交
2100
static int load_tile(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
2101
{
N
nihui 已提交
2102
    struct tile_param* tile_param = (struct tile_param*)node->op.param_mem;
T
Thunder 已提交
2103
    tile_param->frame_flag = 1;
N
nihui 已提交
2104

T
Thunder 已提交
2105 2106 2107
    return 0;
}

T
Thunder 已提交
2108
static int load_cast(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
2109
{
N
nihui 已提交
2110
    struct cast_param* cast_param = (struct cast_param*)node->op.param_mem;
T
Thunder 已提交
2111

N
nihui 已提交
2112
    for (int k = 0; k < onnx_node.attribute_size(); k++)
T
Thunder 已提交
2113 2114
    {
        const onnx::AttributeProto& attr = onnx_node.attribute(k);
N
nihui 已提交
2115
        if (attr.name() == "to")
T
Thunder 已提交
2116 2117 2118 2119 2120 2121 2122
            cast_param->type_to = attr.i();
    }
    cast_param->type_from = 1;

    return 0;
}

T
Thunder 已提交
2123
static int load_depth_to_space(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
2124
{
N
nihui 已提交
2125
    struct depthtospace_param* depthtospace_param = (struct depthtospace_param*)node->op.param_mem;
2126
    depthtospace_param->block_size = GetAttributeOrThrow<int>(onnx_node, "blocksize");
T
Thunder 已提交
2127 2128 2129 2130

    return 0;
}

T
Thunder 已提交
2131
static int load_instance_norm(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
2132
{
N
nihui 已提交
2133
    struct instancenorm_Param* instancenorm_param = (struct instancenorm_Param*)node->op.param_mem;
2134
    instancenorm_param->eps = GetAttributeOrDefault<float>(onnx_node, "epsilon", 1e-5);
T
Thunder 已提交
2135 2136 2137 2138

    return 0;
}

T
Thunder 已提交
2139
static int load_resize(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
2140
{
N
nihui 已提交
2141
    struct interp_param* interp_param = (struct interp_param*)node->op.param_mem;
T
Thunder 已提交
2142 2143
    interp_param->height_scale = 0;
    interp_param->width_scale = 0;
T
Thunder 已提交
2144

2145
    std::string coordinate_transformation_mode = GetAttributeOrDefault<std::string>(onnx_node, "coordinate_transformation_mode", "half_pixel");
2146
    TASSERT(coordinate_transformation_mode == "half_pixel" || coordinate_transformation_mode == "align_corners" || coordinate_transformation_mode == "asymmetric");
2147
    int align_corner = (coordinate_transformation_mode == "align_corners");
2148

N
nihui 已提交
2149
    if (onnx_node.input_size() == 1)
T
Thunder 已提交
2150
    {
N
nihui 已提交
2151
        for (int k = 0; k < onnx_node.attribute_size(); k++)
T
Thunder 已提交
2152 2153
        {
            const onnx::AttributeProto& attr = onnx_node.attribute(k);
N
nihui 已提交
2154
            if (attr.name() == "scales")
T
Thunder 已提交
2155 2156 2157 2158 2159 2160
            {
                interp_param->height_scale = attr.f();
                interp_param->width_scale = attr.f();
            }
        }
    }
N
nihui 已提交
2161
    else if (onnx_node.input_size() == 2) // opset 10
T
Thunder 已提交
2162 2163 2164
    {
        const std::string& input_name = onnx_node.input(1);
        ir_tensor_t* tensor = find_tensor(graph, input_name);
N
nihui 已提交
2165
        float* data = (float*)tensor->data;
T
Thunder 已提交
2166 2167 2168 2169

        interp_param->height_scale = data[2];
        interp_param->width_scale = data[3];
    }
N
nihui 已提交
2170
    else if (onnx_node.input_size() == 3) // opset 11
T
Thunder 已提交
2171 2172 2173
    {
        const std::string& input_name = onnx_node.input(2);
        ir_tensor_t* tensor = find_tensor(graph, input_name);
N
nihui 已提交
2174
        float* data = (float*)tensor->data;
T
Thunder 已提交
2175 2176 2177 2178

        interp_param->height_scale = data[2];
        interp_param->width_scale = data[3];
    }
T
Thunder 已提交
2179 2180
    else if (onnx_node.input_size() == 4)
    {
T
Thunder 已提交
2181 2182
        const std::string& size_name = onnx_node.input(3); // sizes
        ir_tensor_t* size_tensor = find_tensor(graph, size_name);
B
bzhang5 已提交
2183

T
Thunder 已提交
2184 2185 2186 2187 2188 2189
        int64_t* output_dims = (int64_t*)size_tensor->data;
        if (size_tensor->elem_num == 4)
        {
            interp_param->output_height = output_dims[2];
            interp_param->output_width = output_dims[3];
        }
B
bzhang5 已提交
2190
    }
T
Thunder 已提交
2191 2192 2193 2194 2195 2196
    else
    {
        fprintf(stderr, "Not support the num of inputs > 3, please check the onnx model or update the codes of convert tool\n");
        return -1;
    }

2197
    std::string mode = GetAttributeOrDefault<std::string>(onnx_node, "mode", "nearest");
T
Thunder 已提交
2198
    if (mode == "nearest")
T
Thunder 已提交
2199
    {
T
Thunder 已提交
2200
        interp_param->resize_type = 1;
T
Thunder 已提交
2201
    }
T
Thunder 已提交
2202
    else if (mode == "bilinear" || mode == "linear")
T
Thunder 已提交
2203
    {
2204
        interp_param->resize_type = align_corner == 0 ? 2 : 4;
T
Thunder 已提交
2205
    }
T
Thunder 已提交
2206 2207 2208 2209

    return 0;
}

T
Thunder 已提交
2210
static int load_LSTM(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
T
Thunder 已提交
2211
{
N
nihui 已提交
2212
    struct lstm_param* lstm_param = (struct lstm_param*)node->op.param_mem;
T
Thunder 已提交
2213 2214

    lstm_param->mxnet_flag = 0;
2215 2216
    lstm_param->hidden_size = GetAttributeOrThrow<int>(onnx_node, "hidden_size");
    lstm_param->cell_size = lstm_param->hidden_size;
T
Thunder 已提交
2217 2218 2219 2220

    return 0;
}

T
Thunder 已提交
2221
static int load_expand(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
B
bzhang5 已提交
2222
{
N
nihui 已提交
2223
    struct expand_param* expand_param = (struct expand_param*)node->op.param_mem;
B
bzhang5 已提交
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241

    ir_tensor_t* shape_tensor = find_tensor(graph, onnx_node.input(1));
    if (shape_tensor == nullptr)
    {
        fprintf(stderr, "find shape tensor of expand node failed.\n");
        return -1;
    }
    int size = shape_tensor->elem_num;
    expand_param->ex_shape = (int*)sys_malloc(sizeof(int) * size);
    expand_param->dim_num = size;
    int64_t* data = (int64_t*)shape_tensor->data;
    for (int i = 0; i < size; i++)
    {
        expand_param->ex_shape[i] = data[i];
    }
    return 0;
}

T
Thunder 已提交
2242 2243 2244
static int load_gru(ir_graph_t* graph, ir_node_t* node, const onnx::NodeProto& onnx_node)
{
    gru_param* param = (gru_param*)node->op.param_mem;
2245
    param->hidden_size = GetAttributeOrThrow<int>(onnx_node, "hidden_size");
T
Thunder 已提交
2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257
    param->clip = 0;
    param->output_len = 1;
    param->sequence_len = 1;
    param->input_size = 1;
    param->has_clip = 0;
    param->has_gate_bias = 0;
    param->has_candidate_bias = 0;
    param->has_init_state = 0;

    return 0;
}

B
bzhang5 已提交
2258 2259 2260 2261
/*
*   OPERAOTR REGISTER FUNCTION DEFINE FOR ONNX SERIALIZER START
*/
void onnx_serializer::register_op_load()
T
Thunder 已提交
2262
{
N
nihui 已提交
2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291
    op_load_map["Abs"] = std::pair<int, op_load_t>(OP_UNARY, load_unary);
    op_load_map["Acos"] = std::pair<int, op_load_t>(OP_UNARY, load_unary);
    op_load_map["And"] = std::pair<int, op_load_t>(OP_LOGICAL, load_logical);
    op_load_map["ArgMax"] = std::pair<int, op_load_t>(OP_ARGMAX, load_argmax);
    op_load_map["ArgMin"] = std::pair<int, op_load_t>(OP_ARGMIN, load_argmin);
    op_load_map["Asin"] = std::pair<int, op_load_t>(OP_UNARY, load_unary);
    op_load_map["Atan"] = std::pair<int, op_load_t>(OP_UNARY, load_unary);
    op_load_map["AveragePool"] = std::pair<int, op_load_t>(OP_POOL, load_pool);
    op_load_map["Add"] = std::pair<int, op_load_t>(OP_ELTWISE, load_eltwise);
    op_load_map["BatchNormalization"] = std::pair<int, op_load_t>(OP_BATCHNORM, load_bn);
    op_load_map["Conv"] = std::pair<int, op_load_t>(OP_CONV, load_conv);
    op_load_map["ConvTranspose"] = std::pair<int, op_load_t>(OP_DECONV, load_deconv);
    op_load_map["Concat"] = std::pair<int, op_load_t>(OP_CONCAT, load_concat);
    op_load_map["Clip"] = std::pair<int, op_load_t>(OP_CLIP, load_clip);
    op_load_map["Ceil"] = std::pair<int, op_load_t>(OP_UNARY, load_unary);
    op_load_map["Cos"] = std::pair<int, op_load_t>(OP_UNARY, load_unary);
    op_load_map["Cast"] = std::pair<int, op_load_t>(OP_CAST, load_cast);
    op_load_map["Dropout"] = std::pair<int, op_load_t>(OP_DROPOUT, load_no_param);
    op_load_map["DepthToSpace"] = std::pair<int, op_load_t>(OP_DEPTHTOSPACE, load_depth_to_space);
    op_load_map["Div"] = std::pair<int, op_load_t>(OP_ELTWISE, load_eltwise);
    op_load_map["Elu"] = std::pair<int, op_load_t>(OP_ELU, load_elu);
    op_load_map["Exp"] = std::pair<int, op_load_t>(OP_ELTWISE, load_eltwise);
    op_load_map["Expand"] = std::pair<int, op_load_t>(OP_EXPAND, load_expand);
    op_load_map["Equal"] = std::pair<int, op_load_t>(OP_COMPARISON, load_comparison);
    op_load_map["Flatten"] = std::pair<int, op_load_t>(OP_FLATTEN, load_flatten);
    op_load_map["Floor"] = std::pair<int, op_load_t>(OP_ELTWISE, load_eltwise);
    op_load_map["Gemm"] = std::pair<int, op_load_t>(OP_GEMM, load_gemm);
    op_load_map["Gather"] = std::pair<int, op_load_t>(OP_GATHER, load_gather);
    op_load_map["Greater"] = std::pair<int, op_load_t>(OP_COMPARISON, load_comparison);
T
Thunder 已提交
2292
    op_load_map["GRU"] = std::pair<int, op_load_t>(OP_GRU, load_gru);
N
nihui 已提交
2293 2294 2295
    op_load_map["GlobalAveragePool"] = std::pair<int, op_load_t>(OP_POOL, load_pool);
    op_load_map["HardSwish"] = std::pair<int, op_load_t>(OP_HARDSWISH, load_no_param);
    op_load_map["HardSigmoid"] = std::pair<int, op_load_t>(OP_HARDSIGMOID, load_hard_sigmoid);
T
Thunder 已提交
2296
    op_load_map["InstanceNormalization"] = std::pair<int, op_load_t>(OP_INSTANCENORM, load_instance_norm);
N
nihui 已提交
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343
    op_load_map["Log"] = std::pair<int, op_load_t>(OP_UNARY, load_unary);
    op_load_map["LRN"] = std::pair<int, op_load_t>(OP_LRN, load_LRN);
    op_load_map["Less"] = std::pair<int, op_load_t>(OP_COMPARISON, load_comparison);
    op_load_map["LSTM"] = std::pair<int, op_load_t>(OP_LSTM, load_LSTM);
    op_load_map["LeakyRelu"] = std::pair<int, op_load_t>(OP_RELU, load_leaky_relu);
    op_load_map["LogSoftmax"] = std::pair<int, op_load_t>(OP_LOGSOFTMAX, load_log_softmax);
    op_load_map["Mul"] = std::pair<int, op_load_t>(OP_ELTWISE, load_eltwise);
    op_load_map["Max"] = std::pair<int, op_load_t>(OP_MAXIMUM, load_no_param);
    op_load_map["Min"] = std::pair<int, op_load_t>(OP_MINIMUM, load_no_param);
    op_load_map["Mean"] = std::pair<int, op_load_t>(OP_MEAN, load_no_param);
    op_load_map["MatMul"] = std::pair<int, op_load_t>(OP_MATMUL, load_matmul);
    op_load_map["MaxPool"] = std::pair<int, op_load_t>(OP_POOL, load_pool);
    op_load_map["Neg"] = std::pair<int, op_load_t>(OP_UNARY, load_unary);
    op_load_map["Or"] = std::pair<int, op_load_t>(OP_LOGICAL, load_logical);
    op_load_map["Pad"] = std::pair<int, op_load_t>(OP_PAD, load_pad);
    op_load_map["Pow"] = std::pair<int, op_load_t>(OP_ELTWISE, load_eltwise);
    op_load_map["PRelu"] = std::pair<int, op_load_t>(OP_PRELU, load_no_param);
    op_load_map["Relu"] = std::pair<int, op_load_t>(OP_RELU, load_relu);
    op_load_map["Resize"] = std::pair<int, op_load_t>(OP_INTERP, load_resize);
    op_load_map["Reshape"] = std::pair<int, op_load_t>(OP_RESHAPE, load_reshape);
    op_load_map["ReduceL2"] = std::pair<int, op_load_t>(OP_REDUCEL2, load_reducel2);
    op_load_map["ReduceMean"] = std::pair<int, op_load_t>(OP_REDUCTION, load_reduce);
    op_load_map["ReduceLogSumExp"] = std::pair<int, op_load_t>(OP_REDUCTION, load_reduce);
    op_load_map["ReduceLogSum"] = std::pair<int, op_load_t>(OP_REDUCTION, load_reduce);
    op_load_map["ReduceMax"] = std::pair<int, op_load_t>(OP_REDUCTION, load_reduce);
    op_load_map["ReduceMin"] = std::pair<int, op_load_t>(OP_REDUCTION, load_reduce);
    op_load_map["ReduceProd"] = std::pair<int, op_load_t>(OP_REDUCTION, load_reduce);
    op_load_map["ReduceSumSquare"] = std::pair<int, op_load_t>(OP_REDUCTION, load_reduce);
    op_load_map["ReduceSum"] = std::pair<int, op_load_t>(OP_REDUCTION, load_reduce);
    op_load_map["Reciprocal"] = std::pair<int, op_load_t>(OP_RECIPROCAL, load_no_param);
    op_load_map["Sub"] = std::pair<int, op_load_t>(OP_ELTWISE, load_eltwise);
    op_load_map["Selu"] = std::pair<int, op_load_t>(OP_SELU, load_selu);
    op_load_map["Sqrt"] = std::pair<int, op_load_t>(OP_ELTWISE, load_eltwise);
    op_load_map["Slice"] = std::pair<int, op_load_t>(OP_SLICE, load_slice);
    op_load_map["Split"] = std::pair<int, op_load_t>(OP_SPLIT, load_split);
    op_load_map["Shape"] = std::pair<int, op_load_t>(OP_SHAPE, load_no_param);
    op_load_map["Squeeze"] = std::pair<int, op_load_t>(OP_SQUEEZE, load_squeeze);
    op_load_map["Scatter"] = std::pair<int, op_load_t>(OP_SCATTER, load_scatter);
    op_load_map["Sigmoid"] = std::pair<int, op_load_t>(OP_SIGMOID, load_no_param);
    op_load_map["Softmax"] = std::pair<int, op_load_t>(OP_SOFTMAX, load_softmax);
    op_load_map["Softplus"] = std::pair<int, op_load_t>(OP_SOFTPLUS, load_no_param);
    op_load_map["Tanh"] = std::pair<int, op_load_t>(OP_TANH, load_no_param);
    op_load_map["Tile"] = std::pair<int, op_load_t>(OP_TILE, load_tile);
    op_load_map["Transpose"] = std::pair<int, op_load_t>(OP_TRANSPOSE, load_transpose);
    op_load_map["Upsample"] = std::pair<int, op_load_t>(OP_INTERP, load_interp);
    op_load_map["Unsqueeze"] = std::pair<int, op_load_t>(OP_UNSQUEEZE, load_unsqueeze);
    op_load_map["Where"] = std::pair<int, op_load_t>(OP_WHERE, load_no_param);
F
FeiGeChuanShu 已提交
2344
    op_load_map["Gelu"] = std::pair<int, op_load_t>(OP_GELU, load_no_param);
B
bzhang5 已提交
2345 2346
}
/*
T
teng 已提交
2347
*   OPERATOR REGISTER FUNCTION DEFINE FOR ONNX SERIALIZER END
F
FeiGeChuanShu 已提交
2348
*/