cpu_fusion.cpp 180 KB
Newer Older
1
//*****************************************************************************
2
// Copyright 2017-2019 Intel Corporation
3 4 5 6 7 8 9 10 11 12 13 14 15
//
// Licensed 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.
//*****************************************************************************
16 17 18 19 20 21 22 23

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <list>
#include <memory>

#include "gtest/gtest.h"
24
#include "misc.hpp"
25
#include "ngraph/autodiff/adjoints.hpp"
Louis Feng's avatar
Louis Feng committed
26
#include "ngraph/file_util.hpp"
27 28 29
#include "ngraph/graph_util.hpp"
#include "ngraph/log.hpp"
#include "ngraph/ngraph.hpp"
30
#include "ngraph/op/batch_norm.hpp"
31
#include "ngraph/op/concat.hpp"
32
#include "ngraph/op/dequantize.hpp"
gaurides's avatar
gaurides committed
33
#include "ngraph/op/experimental/generate_mask.hpp"
34
#include "ngraph/op/experimental/quantized_conv_bias.hpp"
35
#include "ngraph/op/fused/conv_fused.hpp"
36
#include "ngraph/op/fused/gelu.hpp"
37
#include "ngraph/op/fused/group_conv.hpp"
38
#include "ngraph/op/get_output_element.hpp"
39
#include "ngraph/op/max_pool.hpp"
40
#include "ngraph/op/negative.hpp"
41
#include "ngraph/op/parameter.hpp"
42
#include "ngraph/op/quantize.hpp"
43
#include "ngraph/op/quantized_convolution.hpp"
44
#include "ngraph/op/relu.hpp"
gaurides's avatar
gaurides committed
45
#include "ngraph/op/result.hpp"
Pruthvi's avatar
Pruthvi committed
46
#include "ngraph/op/reverse_sequence.hpp"
47
#include "ngraph/op/sigmoid.hpp"
48
#include "ngraph/op/sum.hpp"
49
#include "ngraph/op/tanh.hpp"
50
#include "ngraph/pass/algebraic_simplification.hpp"
51
#include "ngraph/pass/batch_fusion.hpp"
52
#include "ngraph/pass/core_fusion.hpp"
53 54
#include "ngraph/pass/graph_rewrite.hpp"
#include "ngraph/pass/manager.hpp"
Louis Feng's avatar
Louis Feng committed
55 56
#include "ngraph/pass/reshape_elimination.hpp"
#include "ngraph/pass/visualize_tree.hpp"
57 58
#include "ngraph/pattern/matcher.hpp"
#include "ngraph/pattern/op/label.hpp"
59
#include "ngraph/pattern/op/skip.hpp"
Nick Korovaiko's avatar
Nick Korovaiko committed
60
#include "ngraph/runtime/cpu/cpu_layout_descriptor.hpp"
61
#include "ngraph/runtime/cpu/cpu_tensor_view.hpp"
62
#include "ngraph/runtime/cpu/op/batch_mat_mul_transpose.hpp"
63
#include "ngraph/runtime/cpu/op/batch_norm_relu.hpp"
64
#include "ngraph/runtime/cpu/op/bounded_relu.hpp"
gaurides's avatar
gaurides committed
65
#include "ngraph/runtime/cpu/op/conv_add.hpp"
66
#include "ngraph/runtime/cpu/op/conv_relu.hpp"
Nick Korovaiko's avatar
Nick Korovaiko committed
67
#include "ngraph/runtime/cpu/op/convert_layout.hpp"
gaurides's avatar
gaurides committed
68
#include "ngraph/runtime/cpu/op/deconv.hpp"
gaurides's avatar
gaurides committed
69
#include "ngraph/runtime/cpu/op/dropout.hpp"
70
#include "ngraph/runtime/cpu/op/gelu_backprop.hpp"
71
#include "ngraph/runtime/cpu/op/group_conv_bias.hpp"
72
#include "ngraph/runtime/cpu/op/leaky_relu.hpp"
73
#include "ngraph/runtime/cpu/op/lstm.hpp"
74
#include "ngraph/runtime/cpu/op/matmul_bias.hpp"
75
#include "ngraph/runtime/cpu/op/rnn.hpp"
Pruthvi's avatar
Pruthvi committed
76
#include "ngraph/runtime/cpu/op/rnn_utils.hpp"
77
#include "ngraph/runtime/cpu/op/sigmoid_mul.hpp"
78
#include "ngraph/runtime/cpu/op/update_slice.hpp"
79
#include "ngraph/runtime/cpu/pass/cpu_fusion.hpp"
80
#include "ngraph/runtime/cpu/pass/cpu_mat_fusion.hpp"
Nick Korovaiko's avatar
Nick Korovaiko committed
81
#include "ngraph/runtime/cpu/pass/cpu_post_layout_optimizations.hpp"
82
#include "ngraph/runtime/cpu/pass/cpu_rnn_fusion.hpp"
83
#include "ngraph/runtime/cpu/pass/cpu_workspace_insertion.hpp"
84 85 86
#include "ngraph/serializer.hpp"
#include "ngraph/util.hpp"
#include "util/all_close.hpp"
87
#include "util/all_close_f.hpp"
Pruthvi's avatar
Pruthvi committed
88 89
#include "util/autodiff/backprop_function.hpp"
#include "util/autodiff/numeric_compare.hpp"
90
#include "util/matcher.hpp"
91
#include "util/random.hpp"
92
#include "util/test_tools.hpp"
93

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
using namespace ngraph;
using namespace std;

TEST(cpu_fusion, gemm_pattern)
{
    Shape shape_w{2, 4};
    Shape shape_x{4, 1};
    Shape shape_b{1};
    auto A = make_shared<op::Parameter>(element::f32, shape_w);
    auto B = make_shared<op::Parameter>(element::f32, shape_x);
    auto C = make_shared<op::Parameter>(element::f32, shape_b);

    auto dot = make_shared<op::Dot>(A, B);
    auto broadcast = make_shared<op::Broadcast>(C, dot->get_shape(), AxisSet{0});
    auto add = dot + broadcast;

    auto W = std::make_shared<pattern::op::Label>(A);
    auto x = std::make_shared<pattern::op::Label>(B);

    auto reshape_pred = [](std::shared_ptr<Node> n) {
114
        return static_cast<bool>(as_type_ptr<op::Reshape>(n));
115 116
    };

117 118
    auto skip_w = std::make_shared<pattern::op::Skip>(W, reshape_pred);
    auto skip_x = std::make_shared<pattern::op::Skip>(x, reshape_pred);
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

    auto pdot = make_shared<op::Dot>(skip_w, skip_x);
    auto b = std::make_shared<pattern::op::Label>(C);
    auto pbroadcast = make_shared<op::Broadcast>(b, dot->get_shape(), AxisSet{0});
    auto padd = pdot + pbroadcast;

    TestMatcher n(nullptr);
    ASSERT_TRUE(n.match(padd, add));
    ASSERT_EQ(n.get_pattern_map()[W], A);
    ASSERT_EQ(n.get_pattern_map()[x], B);
    ASSERT_EQ(n.get_pattern_map()[b], C);

    auto reshape_w = make_shared<op::Reshape>(A, AxisVector{1, 0}, W->get_shape());
    auto reshape_x = make_shared<op::Reshape>(B, AxisVector{1, 0}, x->get_shape());
    auto re_dot = make_shared<op::Dot>(reshape_w, reshape_x);
    auto re_add = re_dot + broadcast;
    ASSERT_TRUE(n.match(padd, re_add));
    ASSERT_EQ(n.get_pattern_map()[W], A);
    ASSERT_EQ(n.get_pattern_map()[x], B);
    ASSERT_EQ(n.get_pattern_map()[b], C);

140 141 142 143 144 145 146 147 148 149 150 151
    auto cg = make_shared<op::MatmulBias>(
        W, x, C, W->get_shape(), x->get_shape(), false, false, AxisSet{0});
}

TEST(cpu_fusion, gemm_cpu_broadcast_row)
{
    Shape shapeA{3, 2};
    Shape shapeB{2, 3};
    Shape shapeC{2, 2};
    auto A = make_shared<op::Parameter>(element::f32, shapeA);
    auto B = make_shared<op::Parameter>(element::f32, shapeB);

152
    auto bias = op::Constant::create<float>(element::f32, Shape{2}, std::vector<float>{2.0f, 3.0f});
153 154

    auto cg = make_shared<op::MatmulBias>(
155
        A, B, bias, A->get_shape(), B->get_shape(), true, true, AxisSet{0});
156

157
    auto f = make_shared<Function>(cg, ParameterVector{A, B});
158

159
    auto backend = runtime::Backend::create("CPU");
160

161 162 163
    shared_ptr<runtime::Tensor> a = backend->create_tensor(element::f32, shapeA);
    shared_ptr<runtime::Tensor> b = backend->create_tensor(element::f32, shapeB);
    shared_ptr<runtime::Tensor> result = backend->create_tensor(element::f32, shapeC);
164 165 166 167 168 169

    vector<float> dataA{1.0f, 4.0f, 1.0f, 4.0f, 1.0f, 4.0f};
    vector<float> dataB{3.0f, 3.0f, 3.0f, 9.0f, 9.0f, 9.0f};
    copy_data(a, dataA);
    copy_data(b, dataB);

170
    auto handle = backend->compile(f);
171
    handle->call_with_validate({result}, {a, b});
172
    vector<float> expected{11, 30, 38, 111};
173
    EXPECT_TRUE(test::all_close_f(read_vector<float>(result), expected, MIN_FLOAT_TOLERANCE_BITS));
174 175
}

176 177 178 179 180 181 182 183
TEST(cpu_fusion, gemm_cpu_broadcast_column)
{
    Shape shapeA{3, 2};
    Shape shapeB{2, 3};
    Shape shapeC{2, 2};
    auto A = make_shared<op::Parameter>(element::f32, shapeA);
    auto B = make_shared<op::Parameter>(element::f32, shapeB);

184
    auto bias = op::Constant::create<float>(element::f32, Shape{2}, std::vector<float>{2.0f, 3.0f});
185 186

    auto cg = make_shared<op::MatmulBias>(
187
        A, B, bias, A->get_shape(), B->get_shape(), true, true, AxisSet{1});
188

189
    auto f = make_shared<Function>(cg, ParameterVector{A, B});
190

191
    auto backend = runtime::Backend::create("CPU");
192

193 194 195
    shared_ptr<runtime::Tensor> a = backend->create_tensor(element::f32, shapeA);
    shared_ptr<runtime::Tensor> b = backend->create_tensor(element::f32, shapeB);
    shared_ptr<runtime::Tensor> result = backend->create_tensor(element::f32, shapeC);
196 197 198 199 200 201

    vector<float> dataA{1.0f, 4.0f, 1.0f, 4.0f, 1.0f, 4.0f};
    vector<float> dataB{3.0f, 3.0f, 3.0f, 9.0f, 9.0f, 9.0f};
    copy_data(a, dataA);
    copy_data(b, dataB);

202
    auto handle = backend->compile(f);
203
    handle->call_with_validate({result}, {a, b});
204
    vector<float> expected{11, 29, 39, 111};
205
    EXPECT_TRUE(test::all_close_f(read_vector<float>(result), expected, MIN_FLOAT_TOLERANCE_BITS));
206 207 208
}

TEST(cpu_fusion, gemm_cpu_broadcast_matrix)
209 210 211 212 213 214 215 216 217 218 219 220 221
{
    Shape shapeA{3, 2};
    Shape shapeB{2, 3};
    Shape shapeC{2, 2};
    auto A = make_shared<op::Parameter>(element::f32, shapeA);
    auto B = make_shared<op::Parameter>(element::f32, shapeB);

    auto reshape_w = make_shared<op::Reshape>(A, AxisVector{1, 0}, Shape{2, 3});
    auto reshape_x = make_shared<op::Reshape>(B, AxisVector{1, 0}, Shape{3, 2});

    auto one = op::Constant::create<float>(element::f32, Shape{}, std::vector<float>{1.0f});

    auto broadcast = make_shared<op::Broadcast>(one, shapeC, AxisSet{0, 1});
222 223
    auto cg = make_shared<op::MatmulBias>(
        A, B, one, A->get_shape(), B->get_shape(), true, true, AxisSet{0, 1});
224

225
    auto f = make_shared<Function>(cg, ParameterVector{A, B});
226

227
    auto backend = runtime::Backend::create("CPU");
228

229 230 231
    shared_ptr<runtime::Tensor> a = backend->create_tensor(element::f32, shapeA);
    shared_ptr<runtime::Tensor> b = backend->create_tensor(element::f32, shapeB);
    shared_ptr<runtime::Tensor> result = backend->create_tensor(element::f32, shapeC);
232 233 234 235 236 237

    vector<float> dataA{1.0f, 4.0f, 1.0f, 4.0f, 1.0f, 4.0f};
    vector<float> dataB{3.0f, 3.0f, 3.0f, 9.0f, 9.0f, 9.0f};
    copy_data(a, dataA);
    copy_data(b, dataB);

238
    auto handle = backend->compile(f);
239
    handle->call_with_validate({result}, {a, b});
240
    vector<float> expected{10, 28, 37, 109};
241
    EXPECT_TRUE(test::all_close_f(read_vector<float>(result), expected, MIN_FLOAT_TOLERANCE_BITS));
242 243
}

244 245 246 247 248 249 250 251 252 253 254
TEST(cpu_fusion, gemm_cpu_no_bias)
{
    auto shapeA = Shape{3, 2};
    auto shapeB = Shape{2, 3};
    auto shapeC = Shape{2, 2};
    auto A = make_shared<op::Parameter>(element::f32, shapeA);
    auto B = make_shared<op::Parameter>(element::f32, shapeB);

    auto reshape_w = make_shared<op::Reshape>(A, AxisVector{1, 0}, Shape{2, 3});
    auto reshape_x = make_shared<op::Reshape>(B, AxisVector{1, 0}, Shape{3, 2});

255 256
    auto cg = make_shared<op::MatmulBias>(
        A, B, Output<Node>(), A->get_shape(), B->get_shape(), true, true);
257

258
    auto f = make_shared<Function>(cg, ParameterVector{A, B});
259

260
    auto backend = runtime::Backend::create("CPU");
261

262 263 264
    shared_ptr<runtime::Tensor> a = backend->create_tensor(element::f32, shapeA);
    shared_ptr<runtime::Tensor> b = backend->create_tensor(element::f32, shapeB);
    shared_ptr<runtime::Tensor> result = backend->create_tensor(element::f32, shapeC);
265 266 267 268 269 270

    vector<float> dataA{1.0f, 4.0f, 1.0f, 4.0f, 1.0f, 4.0f};
    vector<float> dataB{3.0f, 3.0f, 3.0f, 9.0f, 9.0f, 9.0f};
    copy_data(a, dataA);
    copy_data(b, dataB);

271
    auto handle = backend->compile(f);
272
    handle->call_with_validate({result}, {a, b});
273
    vector<float> expected{9, 27, 36, 108};
274
    EXPECT_TRUE(test::all_close_f(read_vector<float>(result), expected, MIN_FLOAT_TOLERANCE_BITS));
275 276
}

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
TEST(cpu_fusion, cpu_fusion_pass_basic)
{
    Shape shape{};
    Shape shape_w{2, 4};
    Shape shape_x{4, 1};
    Shape shape_b{1};
    auto A = make_shared<op::Parameter>(element::f32, shape_w);
    auto B = make_shared<op::Parameter>(element::f32, shape_x);
    auto C = make_shared<op::Parameter>(element::f32, shape_b);

    auto dot = make_shared<op::Dot>(A, B);
    auto broadcast = make_shared<op::Broadcast>(C, dot->get_shape(), AxisSet{0});
    auto add = dot + broadcast;
    auto graph = make_shared<op::Abs>(add);
    pass::Manager pass_manager;
292
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
293
    auto func = make_shared<Function>(graph, ParameterVector{A, B, C});
294
    pass_manager.run_passes(func);
295
    ASSERT_NE(as_type_ptr<op::MatmulBias>(graph->get_argument(0)), nullptr);
296 297
}

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
TEST(cpu_fusion, commutative_matmul_bias)
{
    Shape shape{};
    Shape shape_w{2, 4};
    Shape shape_x{4, 1};
    Shape shape_b{1};
    auto A = make_shared<op::Parameter>(element::f32, shape_w);
    auto B = make_shared<op::Parameter>(element::f32, shape_x);
    auto C = make_shared<op::Parameter>(element::f32, shape_b);

    auto dot = make_shared<op::Dot>(A, B);
    auto broadcast = make_shared<op::Broadcast>(C, dot->get_shape(), AxisSet{0});
    auto add = broadcast + dot;
    auto graph = make_shared<op::Abs>(add);
    pass::Manager pass_manager;
313
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
314
    auto func = make_shared<Function>(graph, ParameterVector{A, B, C});
315
    pass_manager.run_passes(func);
316
    ASSERT_NE(as_type_ptr<op::MatmulBias>(graph->get_argument(0)), nullptr);
317 318
}

319 320 321 322 323 324 325 326 327 328
TEST(cpu_fusion, cpu_fusion_pass_matmul_bias)
{
    Shape shape_w{2, 4};
    Shape shape_x{4, 1};
    Shape shape_b{1};
    auto W = make_shared<op::Parameter>(element::f32, shape_w);
    auto x = make_shared<op::Parameter>(element::f32, shape_x);
    auto b = make_shared<op::Parameter>(element::f32, shape_b);

    auto mmb = std::make_shared<op::MatmulBias>(
329
        W, x, Output<Node>(), W->get_shape(), x->get_shape(), false, false);
330 331 332 333 334
    auto broadcast = std::make_shared<op::Broadcast>(b, mmb->get_shape(), AxisSet{0});
    auto add = mmb + broadcast;

    auto graph = make_shared<op::Abs>(add);
    pass::Manager pass_manager;
335
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
336
    auto func = make_shared<Function>(graph, ParameterVector{W, x, b});
337
    pass_manager.run_passes(func);
338
    auto gmm = graph->get_argument(0);
339
    ASSERT_TRUE(as_type_ptr<op::MatmulBias>(gmm));
340
    ASSERT_EQ(gmm->get_argument(2), b);
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
}

TEST(cpu_fusion, cpu_fusion_pass_matmul_no_bias)
{
    Shape shape_w{4, 2};
    Shape shape_x{1, 4};
    auto W = make_shared<op::Parameter>(element::f32, shape_w);
    auto x = make_shared<op::Parameter>(element::f32, shape_x);

    auto reshape_w = std::make_shared<op::Reshape>(W, AxisVector{1, 0}, Shape{2, 4});
    auto reshape_x = std::make_shared<op::Reshape>(x, AxisVector{1, 0}, Shape{4, 1});
    auto re_dot = make_shared<op::Dot>(reshape_w, reshape_x);
    auto graph = make_shared<op::Abs>(re_dot);

    pass::Manager pass_manager;
356
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
357
    auto func = make_shared<Function>(graph, ParameterVector{W, x});
358 359 360 361 362
    pass_manager.run_passes(func);
    size_t mmb = count_ops_of_type<op::MatmulBias>(func);
    ASSERT_EQ(mmb, 1);
}

Louis Feng's avatar
Louis Feng committed
363
struct ConvolutionBiasTestData
Louis Feng's avatar
Louis Feng committed
364
{
Louis Feng's avatar
Louis Feng committed
365 366 367 368 369 370
    size_t n{0};
    size_t c{0};
    size_t filter{0};
    size_t kernel_size{0};
    size_t w{0};
    size_t h{0};
371 372 373 374 375 376 377 378
    shared_ptr<runtime::Tensor> data_val;
    shared_ptr<runtime::Tensor> weights_val;
    shared_ptr<runtime::Tensor> bias_val;
    shared_ptr<runtime::Tensor> result_val;
    shared_ptr<runtime::Tensor> delta_val;
    shared_ptr<runtime::Tensor> d_data_val;
    shared_ptr<runtime::Tensor> d_weights_val;
    shared_ptr<runtime::Tensor> d_bias_val;
Louis Feng's avatar
Louis Feng committed
379 380 381 382 383 384 385 386 387 388 389 390 391 392
    vector<float> expected_result_val;
    vector<float> expected_d_data_val;
    vector<float> expected_d_weights_val;
    vector<float> expected_d_bias_val;

    Shape data_shape;
    Shape weights_shape;
    Shape bias_shape;
    Shape result_shape;
    shared_ptr<op::Parameter> data;
    shared_ptr<op::Parameter> weights;
    shared_ptr<op::Parameter> bias;
    shared_ptr<op::Parameter> delta;

393
    void n1c1h3w3(runtime::Backend* backend)
Louis Feng's avatar
Louis Feng committed
394
    {
Louis Feng's avatar
Louis Feng committed
395 396 397 398 399 400 401 402 403 404 405 406 407
        n = 1;
        c = 1;
        filter = 1;
        kernel_size = 3;
        w = 3;
        h = w;

        data_shape = Shape{n, c, h, w};
        data = make_shared<op::Parameter>(element::f32, data_shape);
        weights_shape = Shape{filter, c, kernel_size, kernel_size};
        weights = make_shared<op::Parameter>(element::f32, weights_shape);
        bias_shape = Shape{filter};
        bias = make_shared<op::Parameter>(element::f32, bias_shape);
Louis Feng's avatar
Louis Feng committed
408
        result_shape = Shape{n, filter, 1, 1};
Louis Feng's avatar
Louis Feng committed
409

410
        data_val = backend->create_tensor(element::f32, data_shape);
Louis Feng's avatar
Louis Feng committed
411 412 413 414 415 416 417 418 419 420
        copy_data(data_val,
                  vector<float>{-0.67765152f,
                                0.10073948f,
                                0.57595438f,
                                -0.3469252f,
                                -0.22134334f,
                                -1.80471897f,
                                -0.80642909f,
                                1.22033095f,
                                2.23235631f});
421
        weights_val = backend->create_tensor(element::f32, weights_shape);
Louis Feng's avatar
Louis Feng committed
422 423 424 425 426 427 428 429 430 431
        copy_data(weights_val,
                  vector<float>{0.20070229f,
                                -0.54968649f,
                                -0.19819015f,
                                -0.38577855f,
                                1.37109005f,
                                -0.23789984f,
                                0.14867957f,
                                -0.49851316f,
                                -0.84815776f});
432
        bias_val = backend->create_tensor(element::f32, bias_shape);
Louis Feng's avatar
Louis Feng committed
433 434
        copy_data(bias_val, vector<float>{0.07811152f});

435
        result_val = backend->create_tensor(element::f32, result_shape);
Louis Feng's avatar
Louis Feng committed
436 437 438
        copy_data(result_val, vector<float>{0});

        delta = make_shared<op::Parameter>(element::f32, result_shape);
439
        delta_val = backend->create_tensor(element::f32, result_shape);
Louis Feng's avatar
Louis Feng committed
440 441
        copy_data(delta_val, vector<float>{-2.58936238f});

442
        d_data_val = backend->create_tensor(element::f32, data_shape);
Louis Feng's avatar
Louis Feng committed
443
        copy_data(d_data_val, vector<float>{0, 0, 0, 0, 0, 0, 0, 0, 0});
Louis Feng's avatar
Louis Feng committed
444

445
        d_weights_val = backend->create_tensor(element::f32, weights_shape);
Louis Feng's avatar
Louis Feng committed
446
        copy_data(d_weights_val, vector<float>{0, 0, 0, 0, 0, 0, 0, 0, 0});
Louis Feng's avatar
Louis Feng committed
447

448
        d_bias_val = backend->create_tensor(element::f32, bias_shape);
Louis Feng's avatar
Louis Feng committed
449 450
        copy_data(d_bias_val, vector<float>{0});

Louis Feng's avatar
Louis Feng committed
451
        expected_result_val = vector<float>{-2.58936238f};
Louis Feng's avatar
Louis Feng committed
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
        expected_d_data_val = vector<float>{-0.51969099f,
                                            1.42333758f,
                                            0.5131861f,
                                            0.99892044f,
                                            -3.5502491f,
                                            0.61600888f,
                                            -0.3849853f,
                                            1.29083121f,
                                            2.19618773f};
        expected_d_weights_val = vector<float>{1.7546854f,
                                               -0.26085103f,
                                               -1.49135458f,
                                               0.89831507f,
                                               0.57313812f,
                                               4.67307138f,
                                               2.08813715f,
                                               -3.15987897f,
                                               -5.7803793f};
Louis Feng's avatar
Louis Feng committed
470
        expected_d_bias_val = vector<float>{-2.58936238f};
Louis Feng's avatar
Louis Feng committed
471
    }
Louis Feng's avatar
Louis Feng committed
472
};
Louis Feng's avatar
Louis Feng committed
473

Louis Feng's avatar
Louis Feng committed
474
TEST(cpu_fusion, conv_bias_fprop_n1c1h3w3)
Louis Feng's avatar
Louis Feng committed
475
{
476
    auto backend = runtime::Backend::create("CPU");
Louis Feng's avatar
Louis Feng committed
477 478

    ConvolutionBiasTestData conv_test;
479
    conv_test.n1c1h3w3(backend.get());
Louis Feng's avatar
Louis Feng committed
480 481 482 483

    auto convolution = make_shared<op::Convolution>(conv_test.data, conv_test.weights);
    auto convolution_bias = make_shared<op::ConvolutionBias>(convolution, conv_test.bias);

Louis Feng's avatar
Louis Feng committed
484
    auto f = make_shared<Function>(
485
        convolution_bias, ParameterVector{conv_test.data, conv_test.weights, conv_test.bias});
Louis Feng's avatar
Louis Feng committed
486

487
    auto handle = backend->compile(f);
488 489
    handle->call_with_validate({conv_test.result_val},
                               {conv_test.data_val, conv_test.weights_val, conv_test.bias_val});
Louis Feng's avatar
Louis Feng committed
490
    auto result_vec = read_vector<float>(conv_test.result_val);
Louis Feng's avatar
Louis Feng committed
491

Louis Feng's avatar
Louis Feng committed
492 493
    EXPECT_TRUE(
        test::all_close(conv_test.expected_result_val, read_vector<float>(conv_test.result_val)));
Louis Feng's avatar
Louis Feng committed
494 495
}

Louis Feng's avatar
Louis Feng committed
496
TEST(cpu_fusion, conv_bias_bprop_n1c1h3w3)
Louis Feng's avatar
Louis Feng committed
497
{
498
    auto backend = runtime::Backend::create("CPU");
Louis Feng's avatar
Louis Feng committed
499

Louis Feng's avatar
Louis Feng committed
500
    ConvolutionBiasTestData conv_test;
501
    conv_test.n1c1h3w3(backend.get());
Louis Feng's avatar
Louis Feng committed
502 503 504 505

    auto convolution = make_shared<op::Convolution>(conv_test.data, conv_test.weights);
    auto convolution_bias = make_shared<op::ConvolutionBias>(convolution, conv_test.bias);

Louis Feng's avatar
Louis Feng committed
506
    auto f = make_shared<Function>(
507
        convolution_bias, ParameterVector{conv_test.data, conv_test.weights, conv_test.bias});
Louis Feng's avatar
Louis Feng committed
508

509 510
    ngraph::autodiff::Adjoints adjoints(OutputVector{convolution_bias},
                                        OutputVector{conv_test.delta});
511 512 513 514

    auto d_data = adjoints.backprop_node(conv_test.data);
    auto d_weights = adjoints.backprop_node(conv_test.weights);
    auto d_bias = adjoints.backprop_node(conv_test.bias);
Louis Feng's avatar
Louis Feng committed
515

Louis Feng's avatar
Louis Feng committed
516 517
    auto df = make_shared<Function>(
        NodeVector{d_data, d_weights, d_bias},
518
        ParameterVector{conv_test.data, conv_test.weights, conv_test.bias, conv_test.delta});
519 520 521
    auto handle = backend->compile(df);
    handle->call_with_validate(

522 523
        {conv_test.d_data_val, conv_test.d_weights_val, conv_test.d_bias_val},
        {conv_test.data_val, conv_test.weights_val, conv_test.bias_val, conv_test.delta_val});
Louis Feng's avatar
Louis Feng committed
524

Louis Feng's avatar
Louis Feng committed
525 526 527 528 529 530
    EXPECT_TRUE(
        test::all_close(conv_test.expected_d_data_val, read_vector<float>(conv_test.d_data_val)));
    EXPECT_TRUE(test::all_close(conv_test.expected_d_weights_val,
                                read_vector<float>(conv_test.d_weights_val)));
    EXPECT_TRUE(
        test::all_close(conv_test.expected_d_bias_val, read_vector<float>(conv_test.d_bias_val)));
Louis Feng's avatar
Louis Feng committed
531
}
Pruthvi's avatar
Pruthvi committed
532

533 534 535 536 537 538
TEST(cpu_fusion, conv_bias_bprop)
{
    Shape shape{2, 2, 1, 1};
    auto data_batch = std::make_shared<op::Parameter>(element::f32, shape);
    auto filters = std::make_shared<op::Parameter>(element::f32, shape);
    auto delta = std::make_shared<op::Parameter>(element::f32, shape);
539 540
    auto bias = make_shared<op::Parameter>(element::f32, Shape{shape[0]});
    auto pbroadcast = std::make_shared<op::Broadcast>(bias, shape, AxisSet{1, 2, 3});
541 542 543 544 545
    auto conv = std::make_shared<op::Convolution>(data_batch, filters);
    auto conv_bias = std::make_shared<op::Add>(conv, pbroadcast);

    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
546
    pass_manager.register_pass<pass::VisualizeTree>("conv_bias_bprop_fusion.png");
547
    auto f = make_shared<Function>(conv_bias, ParameterVector{data_batch, filters, bias});
548

549
    ngraph::autodiff::Adjoints adjoints(OutputVector{conv_bias}, OutputVector{delta});
550 551 552 553 554 555

    auto d_data = adjoints.backprop_node(data_batch);
    auto d_weights = adjoints.backprop_node(filters);
    auto d_bias = adjoints.backprop_node(bias);

    auto df = make_shared<Function>(NodeVector{d_data, d_weights, d_bias},
556
                                    ParameterVector{data_batch, filters, bias, delta});
557 558 559 560 561 562

    pass_manager.run_passes(df);
    size_t ccg = count_ops_of_type<op::ConvolutionBiasBackpropFiltersBias>(df);
    ASSERT_EQ(ccg, 1);
}

563
static void test_batchnorm_multiply_add_relu(Shape input_shape)
Amy Zhuang's avatar
Amy Zhuang committed
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
{
    auto make_bn_relu_function = [&]() {
        auto c_axis = input_shape[1];
        auto input = make_shared<op::Parameter>(element::f32, input_shape);
        auto mean_shape = Shape{c_axis};
        auto mean = std::make_shared<op::Parameter>(element::f32, mean_shape);
        auto var_shape = Shape{c_axis};
        auto var = std::make_shared<op::Parameter>(element::f32, var_shape);
        auto gamma_shape = Shape{c_axis};
        auto gamma = make_shared<op::Parameter>(element::f32, gamma_shape);
        auto beta_shape = Shape{c_axis};
        auto beta = make_shared<op::Parameter>(element::f32, beta_shape);
        double eps = 0.001;
        auto bn =
            std::make_shared<ngraph::op::BatchNormInference>(eps, gamma, beta, input, mean, var);

        std::vector<size_t> vec{0};
581
        for (size_t i = 2; i < input_shape.size(); i++)
Amy Zhuang's avatar
Amy Zhuang committed
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
        {
            vec.push_back(i);
        }
        auto broadcast1_input = std::make_shared<op::Parameter>(element::f32, gamma_shape);
        auto broadcast1 =
            std::make_shared<ngraph::op::Broadcast>(broadcast1_input, input_shape, AxisSet(vec));
        auto multiply = std::make_shared<ngraph::op::Multiply>(bn, broadcast1);

        auto broadcast2_input = std::make_shared<op::Parameter>(element::f32, gamma_shape);
        auto broadcast2 =
            std::make_shared<ngraph::op::Broadcast>(broadcast2_input, input_shape, AxisSet(vec));

        auto add = std::make_shared<ngraph::op::Add>(multiply, broadcast2);
        auto relu = std::make_shared<ngraph::op::Relu>(add);
        auto f = make_shared<Function>(
            relu,
            ParameterVector{gamma, beta, input, mean, var, broadcast1_input, broadcast2_input});
        return f;
    };

    auto cpu_f = make_bn_relu_function();
    auto int_f = make_bn_relu_function();
604
    test::Uniform<float> rng(1.0f, 10.0f);
Amy Zhuang's avatar
Amy Zhuang committed
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
    vector<vector<float>> args;

    for (shared_ptr<op::Parameter> param : int_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f));
    }

    size_t bn_relu = count_ops_of_type<op::BatchNormInferenceRelu>(cpu_f);
    ASSERT_EQ(bn_relu, 1);
}

624
TEST(cpu_fusion, MLIR_DISABLE_TEST(batchnorm_multiply_add_relu))
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
{
    test_batchnorm_multiply_add_relu(Shape{1, 3, 2, 2});
    test_batchnorm_multiply_add_relu(Shape{1, 2, 2, 2, 2});
    test_batchnorm_multiply_add_relu(Shape{2, 2, 2, 4, 4});
}

TEST(cpu_fusion, batchnorm_multiply_add_relu_no_fusion)
{
    auto input_shape = Shape{3, 3, 2, 2};
    auto make_bn_relu_function = [&]() {
        auto c_axis = input_shape[1];
        auto input = make_shared<op::Parameter>(element::f32, input_shape);
        auto mean_shape = Shape{c_axis};
        auto mean = std::make_shared<op::Parameter>(element::f32, mean_shape);
        auto var_shape = Shape{c_axis};
        auto var = std::make_shared<op::Parameter>(element::f32, var_shape);
        auto gamma_shape = Shape{c_axis};
        auto gamma = make_shared<op::Parameter>(element::f32, gamma_shape);
        auto beta_shape = Shape{c_axis};
        auto beta = make_shared<op::Parameter>(element::f32, beta_shape);
        double eps = 0.001;
        auto bn =
            std::make_shared<ngraph::op::BatchNormInference>(eps, gamma, beta, input, mean, var);

        std::vector<size_t> vec;
650
        for (size_t i = 1; i < input_shape.size(); i++)
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
        {
            vec.push_back(i);
        }
        auto broadcast1_input = std::make_shared<op::Parameter>(element::f32, Shape{3});
        auto broadcast1 =
            std::make_shared<ngraph::op::Broadcast>(broadcast1_input, input_shape, AxisSet(vec));
        auto multiply = std::make_shared<ngraph::op::Multiply>(bn, broadcast1);

        auto broadcast2_input = std::make_shared<op::Parameter>(element::f32, Shape{3});
        auto broadcast2 =
            std::make_shared<ngraph::op::Broadcast>(broadcast2_input, input_shape, AxisSet(vec));

        auto add = std::make_shared<ngraph::op::Add>(multiply, broadcast2);
        auto relu = std::make_shared<ngraph::op::Relu>(add);
        auto f = make_shared<Function>(
            relu,
            ParameterVector{gamma, beta, input, mean, var, broadcast1_input, broadcast2_input});
        return f;
    };

    auto cpu_f = make_bn_relu_function();
    auto int_f = make_bn_relu_function();
    test::Uniform<float> rng(1.0f, 10.0f);
    vector<vector<float>> args;

    for (shared_ptr<op::Parameter> param : int_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f));
    }

    size_t bn_relu = count_ops_of_type<op::BatchNormInferenceRelu>(cpu_f);
    ASSERT_EQ(bn_relu, 0);
}

693 694 695 696 697 698 699 700 701 702 703 704
TEST(cpu_fusion, batchnorm_fprop_relu_b1c2h2w2)
{
    auto input_shape = Shape{1, 2, 2, 2};
    auto input = make_shared<op::Parameter>(element::f32, input_shape);
    auto mean_shape = Shape{2};
    auto var_shape = Shape{2};
    auto gamma_shape = Shape{2};
    auto gamma = make_shared<op::Parameter>(element::f32, gamma_shape);
    auto beta_shape = Shape{2};
    auto beta = make_shared<op::Parameter>(element::f32, beta_shape);
    double eps = 0.001;
    auto shape_r = Shape{1, 2, 2, 2};
705
    auto bn = make_shared<op::BatchNormTraining>(input, gamma, beta, eps);
706 707 708 709 710 711 712 713 714 715 716 717 718

    auto output_rt = std::make_shared<op::GetOutputElement>(bn, 0);
    // Note, op::Splice is used to break Relu(BatchNorm) fusion
    // otherwise we will be comparing two BatchNormRelus
    // Unfortunately, we can't use INTERPRETER for
    // verifying the results as it doesn't implement
    // BatchNorm op.
    auto slice =
        std::make_shared<op::Slice>(output_rt, Coordinate{0, 0, 0, 0}, Coordinate{1, 2, 2, 2});
    auto output_relu = std::make_shared<op::Relu>(slice);
    auto mean_rt = std::make_shared<op::GetOutputElement>(bn, 1);
    auto variance_rt = std::make_shared<op::GetOutputElement>(bn, 2);

719
    auto bn_relu = make_shared<op::BatchNormTrainingRelu>(eps, gamma, beta, input);
720 721 722 723 724 725
    auto output_rt_bnr = std::make_shared<op::GetOutputElement>(bn_relu, 0);
    auto mean_rt_bnr = std::make_shared<op::GetOutputElement>(bn_relu, 1);
    auto variance_rt_bnr = std::make_shared<op::GetOutputElement>(bn_relu, 2);

    auto f = make_shared<Function>(
        NodeVector{output_relu, mean_rt, variance_rt, output_rt_bnr, mean_rt_bnr, variance_rt_bnr},
726
        ParameterVector{input, gamma, beta});
727
    auto backend = runtime::Backend::create("CPU");
728 729

    // Create some tensors for input/output
730
    auto input_t = backend->create_tensor(element::f32, Shape{1, 2, 2, 2});
731 732 733 734 735 736 737 738 739 740

    copy_data(input_t,
              vector<float>{0.54881352f,
                            0.71518934f,
                            0.60276335f,
                            0.54488319f,
                            0.42365479f,
                            0.64589411f,
                            0.4375872f,
                            0.89177299f});
741
    auto gamma_t = backend->create_tensor(element::f32, gamma_shape);
742
    copy_data(gamma_t, vector<float>{1.0f, 1.0f});
743
    auto beta_t = backend->create_tensor(element::f32, beta_shape);
744
    copy_data(beta_t, vector<float>{0.0f, 0.0f});
745 746 747 748 749 750 751 752
    auto bn_output = backend->create_tensor(element::f32, shape_r);
    auto result_mean = backend->create_tensor(element::f32, mean_shape);
    auto result_variance = backend->create_tensor(element::f32, var_shape);

    auto bn_output_bnr = backend->create_tensor(element::f32, shape_r);
    auto result_mean_bnr = backend->create_tensor(element::f32, mean_shape);
    auto result_variance_bnr = backend->create_tensor(element::f32, var_shape);

753
    auto handle = backend->compile(f);
754 755 756 757 758 759 760
    handle->call_with_validate({bn_output,
                                result_mean,
                                result_variance,
                                bn_output_bnr,
                                result_mean_bnr,
                                result_variance_bnr},
                               {input_t, gamma_t, beta_t});
761 762 763 764 765 766 767 768

    EXPECT_TRUE(test::all_close(read_vector<float>(bn_output), read_vector<float>(bn_output_bnr)));
    EXPECT_TRUE(
        test::all_close(read_vector<float>(result_mean), read_vector<float>(result_mean_bnr)));
    EXPECT_TRUE(test::all_close(read_vector<float>(result_variance),
                                read_vector<float>(result_variance_bnr)));
}

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
static void test_batchnorm_fprop_relu(Shape input_shape)
{
    auto make_bn_relu_function = [&]() {
        auto c_axis = input_shape[1];
        auto input = make_shared<op::Parameter>(element::f32, input_shape);
        auto mean_shape = Shape{c_axis};
        auto var_shape = Shape{c_axis};
        auto gamma_shape = Shape{c_axis};
        auto gamma = make_shared<op::Parameter>(element::f32, gamma_shape);
        auto beta_shape = Shape{c_axis};
        auto beta = make_shared<op::Parameter>(element::f32, beta_shape);
        double eps = 0.001;
        auto shape_r = input_shape;
        auto bn = make_shared<op::BatchNormTraining>(eps, gamma, beta, input);
        auto output_rt = std::make_shared<op::GetOutputElement>(bn, 0);

        auto output_relu = std::make_shared<op::Relu>(output_rt);
        auto mean_rt = std::make_shared<op::GetOutputElement>(bn, 1);
        auto variance_rt = std::make_shared<op::GetOutputElement>(bn, 2);

        auto f = make_shared<Function>(NodeVector{output_relu, mean_rt, variance_rt},
                                       ParameterVector{input, gamma, beta});
        return f;
    };
    auto cpu_f = make_bn_relu_function();
    auto int_f = make_bn_relu_function();
    test::Uniform<float> rng(-10.0f, 10.0f);
    vector<vector<float>> args;

    for (shared_ptr<op::Parameter> param : int_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f));
    }
}

TEST(cpu_fusion, batchnorm_fprop_relu)
{
    test_batchnorm_fprop_relu(Shape{1, 2, 2, 2});
    test_batchnorm_fprop_relu(Shape{1, 2, 2, 2, 2});
    test_batchnorm_fprop_relu(Shape{2, 2, 2, 4, 4});
}

819 820 821 822 823 824 825 826
TEST(cpu_fusion, fuse_conv_relu)
{
    auto A = std::make_shared<op::Parameter>(element::f32, Shape{2, 1, 2, 2});
    auto weights = std::make_shared<op::Parameter>(element::f32, Shape{1, 1, 2, 2});
    auto convolution = std::make_shared<op::Convolution>(A, weights, Strides{1, 1}, Strides{1, 1});
    auto relu = std::make_shared<op::Relu>(convolution);
    auto abs_node =
        std::make_shared<op::Abs>(std::make_shared<op::Abs>(std::make_shared<op::Abs>(relu)));
827
    auto func = make_shared<Function>(abs_node, ParameterVector{A, weights});
828 829

    pass::Manager pass_manager;
830
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
831 832 833 834 835
    pass_manager.run_passes(func);
    size_t cb = count_ops_of_type<op::ConvolutionRelu>(func);
    ASSERT_GT(cb, 0);
}

836
TEST(cpu_fusion, conv_relu_n2c1h2w2_2)
837 838 839 840
{
    Shape shape_a{2, 1, 6, 6};
    Shape shape_weights{1, 1, 2, 2};

841 842 843 844 845
    auto make_int_function = [shape_a, shape_weights]() {
        auto A = std::make_shared<op::Parameter>(element::f32, shape_a);
        auto weights = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto conv = std::make_shared<op::Convolution>(A, weights, Strides{2, 2}, Strides{1, 1});
        auto relu = std::make_shared<op::Relu>(conv);
846
        auto f = make_shared<Function>(NodeVector{relu}, ParameterVector{A, weights});
847 848
        return f;
    };
849

850
    auto int_f = make_int_function();
851

852 853 854 855 856
    auto make_cpu_function = [shape_a, shape_weights]() {
        auto A = std::make_shared<op::Parameter>(element::f32, shape_a);
        auto weights = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto conv = std::make_shared<op::Convolution>(A, weights, Strides{2, 2}, Strides{1, 1});
        auto conv_relu = std::make_shared<op::ConvolutionRelu>(conv);
857
        auto f = make_shared<Function>(NodeVector{conv_relu}, ParameterVector{A, weights});
858 859
        return f;
    };
860

861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
    auto cpu_f = make_cpu_function();

    vector<vector<float>> args{
        {1.25f,  2.25f, 5.25f, 6.25f,  -1.25f, -1.25f, 3.25f, -4.25f, 7.25f,  8.25f,  -1.25f,
         -1.25f, 1.25f, 2.25f, -3.25f, 2.25f,  4.25f,  4.25f, 1.25f,  2.25f,  -4.25f, 2.25f,
         4.25f,  4.25f, 0.f,   0.f,    -1.f,   0.f,    2.f,   2.f,    0.f,    0.f,    0.f,
         0.f,    2.f,   2.f,   1.25f,  2.25f,  5.25f,  6.25f, 1.25f,  1.25f,  3.25f,  4.25f,
         -7.25f, 8.25f, 1.25f, -1.25f, -1.25f, 2.25f,  3.25f, 2.25f,  -4.25f, -4.25f, -1.25f,
         -2.25f, 4.25f, 2.25f, 4.25f,  4.25f,  0.f,    0.f,   1.f,    0.f,    -2.f,   2.f,
         0.f,    0.f,   0.f,   0.f,    -2.f,   -2.f},
        {2., 2., 2., 2.}};

    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu_results.at(0), int_results.at(0)));
}
877

878 879 880 881 882 883 884 885 886 887 888 889 890 891
TEST(cpu_fusion, conv_bias_relu_n2c1h2w2_2)
{
    Shape shape_a{2, 1, 6, 6};
    Shape shape_weights{1, 1, 2, 2};
    Shape shape_bias{1};

    auto make_int_function = [shape_a, shape_weights, shape_bias]() {
        auto A = std::make_shared<op::Parameter>(element::f32, shape_a);
        auto weights = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto conv = std::make_shared<op::Convolution>(A, weights, Strides{2, 2}, Strides{1, 1});
        auto bias = std::make_shared<op::Parameter>(element::f32, shape_bias);
        auto conv_bias =
            conv + std::make_shared<op::Broadcast>(bias, conv->get_shape(), AxisSet{0, 2, 3});
        auto relu = std::make_shared<op::Relu>(conv_bias);
892
        auto f = make_shared<Function>(NodeVector{relu}, ParameterVector{A, weights, bias});
893 894 895 896 897 898 899 900 901 902
        return f;
    };

    auto int_f = make_int_function();

    auto make_cpu_function = [shape_a, shape_weights, shape_bias]() {
        auto A = std::make_shared<op::Parameter>(element::f32, shape_a);
        auto weights = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto bias = std::make_shared<op::Parameter>(element::f32, shape_bias);
        auto conv = std::make_shared<op::Convolution>(A, weights, Strides{2, 2}, Strides{1, 1});
903
        auto conv_bias_relu = std::make_shared<op::ConvolutionBias>(conv, bias, true);
904 905
        auto f =
            make_shared<Function>(NodeVector{conv_bias_relu}, ParameterVector{A, weights, bias});
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
        return f;
    };

    auto cpu_f = make_cpu_function();

    vector<vector<float>> args{
        {1.25f,  2.25f, 5.25f, 6.25f,  -1.25f, -1.25f, 3.25f, -4.25f, 7.25f,  8.25f,  -1.25f,
         -1.25f, 1.25f, 2.25f, -3.25f, 2.25f,  4.25f,  4.25f, 1.25f,  2.25f,  -4.25f, 2.25f,
         4.25f,  4.25f, 0.f,   0.f,    -1.f,   0.f,    2.f,   2.f,    0.f,    0.f,    0.f,
         0.f,    2.f,   2.f,   1.25f,  2.25f,  5.25f,  6.25f, 1.25f,  1.25f,  3.25f,  4.25f,
         -7.25f, 8.25f, 1.25f, -1.25f, -1.25f, 2.25f,  3.25f, 2.25f,  -4.25f, -4.25f, -1.25f,
         -2.25f, 4.25f, 2.25f, 4.25f,  4.25f,  0.f,    0.f,   1.f,    0.f,    -2.f,   2.f,
         0.f,    0.f,   0.f,   0.f,    -2.f,   -2.f},
        {2., 2., 2., 2.},
        {0.1f}};

    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu_results.at(0), int_results.at(0)));
}

927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
TEST(cpu_fusion, conv_horizontal_fusion)
{
    Shape shape_a{2, 1, 6, 6};
    Shape shape_weights{1, 1, 2, 2};
    Shape shape_bias{1};

    auto make_function = [shape_a, shape_weights, shape_bias]() {
        auto A = std::make_shared<op::Parameter>(element::f32, shape_a);
        auto weights1 = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto conv1 = std::make_shared<op::Convolution>(A, weights1, Strides{2, 2}, Strides{1, 1});
        auto bias1 = std::make_shared<op::Parameter>(element::f32, shape_bias);
        auto conv_bias1 =
            conv1 + std::make_shared<op::Broadcast>(bias1, conv1->get_shape(), AxisSet{0, 2, 3});
        auto relu1 = std::make_shared<op::Relu>(conv_bias1);

        auto weights2 = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto conv2 = std::make_shared<op::Convolution>(A, weights2, Strides{2, 2}, Strides{1, 1});
        auto bias2 = std::make_shared<op::Parameter>(element::f32, shape_bias);
        auto conv_bias2 =
            conv2 + std::make_shared<op::Broadcast>(bias2, conv2->get_shape(), AxisSet{0, 2, 3});
        auto relu2 = std::make_shared<op::Relu>(conv_bias2);

        auto concat = std::make_shared<op::Concat>(NodeVector{relu1, relu2}, 1);
        auto f = make_shared<Function>(NodeVector{concat},
951
                                       ParameterVector{A, weights1, bias1, weights2, bias2});
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
        return f;
    };
    auto int_f = make_function();
    auto cpu_f = make_function();

    vector<vector<float>> args{
        {1.25f,  2.25f, 5.25f, 6.25f,  -1.25f, -1.25f, 3.25f, -4.25f, 7.25f,  8.25f,  -1.25f,
         -1.25f, 1.25f, 2.25f, -3.25f, 2.25f,  4.25f,  4.25f, 1.25f,  2.25f,  -4.25f, 2.25f,
         4.25f,  4.25f, 0.f,   0.f,    -1.f,   0.f,    2.f,   2.f,    0.f,    0.f,    0.f,
         0.f,    2.f,   2.f,   1.25f,  2.25f,  5.25f,  6.25f, 1.25f,  1.25f,  3.25f,  4.25f,
         -7.25f, 8.25f, 1.25f, -1.25f, -1.25f, 2.25f,  3.25f, 2.25f,  -4.25f, -4.25f, -1.25f,
         -2.25f, 4.25f, 2.25f, 4.25f,  4.25f,  0.f,    0.f,   1.f,    0.f,    -2.f,   2.f,
         0.f,    0.f,   0.f,   0.f,    -2.f,   -2.f},
        {2., 2., 2., 2.},
        {0.1f},
        {3., 3., 3., 3.},
        {0.2f}};

    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu_results.at(0), int_results.at(0)));

    size_t cpu_cb = count_ops_of_type<op::ConvolutionBias>(cpu_f);
    ASSERT_EQ(cpu_cb, 1);
}

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
// ConvolutionBiasAdd relies on an in-place fused MKLDNN kernel.
// Need to ensure that it is fused only when in-place buffer allocation is feasible
shared_ptr<Function> gen_conv_bias_add(bool param_input, bool result_output)
{
    auto A = make_shared<op::Parameter>(element::f32, Shape{2, 1, 2, 2});
    auto weights = make_shared<op::Parameter>(element::f32, Shape{1, 1, 1, 1});
    auto bias = make_shared<op::Parameter>(element::f32, Shape{1});
    auto conv = make_shared<op::Convolution>(A, weights, Strides{1, 1}, Strides{1, 1});
    auto bias_broadcast = make_shared<op::Broadcast>(bias, conv->get_shape(), AxisSet{0, 2, 3});
    auto convbias = conv + bias_broadcast;
    auto B = make_shared<op::Parameter>(element::f32, Shape{2, 1, 2, 2});
    auto abs_B = make_shared<op::Abs>(B);
    auto add =
        param_input ? make_shared<op::Add>(convbias, B) : make_shared<op::Add>(convbias, abs_B);
    auto abs = make_shared<op::Abs>(add);

994 995
    return result_output ? make_shared<Function>(add, ParameterVector{A, weights, bias, B})
                         : make_shared<Function>(abs, ParameterVector{A, weights, bias, B});
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
}

TEST(cpu_fusion, fuse_conv_bias_add)
{
    auto func_fuse = gen_conv_bias_add(false, false);
    auto func_nofuse1 = gen_conv_bias_add(true, false);
    auto func_nofuse2 = gen_conv_bias_add(false, true);

    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
    pass_manager.run_passes(func_fuse);
    ASSERT_EQ(count_ops_of_type<op::ConvolutionBiasAdd>(func_fuse), 1);

    pass_manager.run_passes(func_nofuse1);
    ASSERT_EQ(count_ops_of_type<op::ConvolutionBiasAdd>(func_nofuse1), 0);

    pass_manager.run_passes(func_nofuse2);
gaurides's avatar
gaurides committed
1013
    ASSERT_EQ(count_ops_of_type<op::ConvolutionBiasAdd>(func_nofuse2), 1);
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
}

TEST(cpu_fusion, conv_bias_add)
{
    auto int_f = gen_conv_bias_add(false, false);
    auto cpu_f = gen_conv_bias_add(false, false);

    vector<vector<float>> args{{1.25f, 2.25f, 5.25f, 6.25f, -1.25f, -1.25f, 3.25f, -4.25f},
                               {-1.25f},
                               {2.25f},
                               {1.25f, 2.25f, -3.25f, 2.25f, 4.25f, 4.25f, 1.25f, 2.25f}};

    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu_results.at(0), int_results.at(0)));
}

gaurides's avatar
gaurides committed
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
// ConvolutionAdd relies on an in-place fused MKLDNN kernel.
// Need to ensure that it is fused only when in-place buffer allocation is feasible
shared_ptr<Function> gen_conv_add(bool param_input, bool result_output)
{
    auto A = make_shared<op::Parameter>(element::f32, Shape{2, 1, 2, 2});
    auto weights = make_shared<op::Parameter>(element::f32, Shape{1, 1, 1, 1});
    auto conv = make_shared<op::Convolution>(A, weights, Strides{1, 1}, Strides{1, 1});
    auto B = make_shared<op::Parameter>(element::f32, Shape{2, 1, 2, 2});
    auto abs_B = make_shared<op::Abs>(B);
    auto add = param_input ? make_shared<op::Add>(conv, B) : make_shared<op::Add>(conv, abs_B);
    auto abs = make_shared<op::Abs>(add);

1043 1044
    return result_output ? make_shared<Function>(add, ParameterVector{A, weights, B})
                         : make_shared<Function>(abs, ParameterVector{A, weights, B});
gaurides's avatar
gaurides committed
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
}

TEST(cpu_fusion, fuse_conv_add)
{
    auto func_fuse = gen_conv_add(false, false);
    auto func_nofuse1 = gen_conv_add(true, false);
    auto func_nofuse2 = gen_conv_add(false, true);

    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
    pass_manager.run_passes(func_fuse);
    ASSERT_EQ(count_ops_of_type<op::ConvolutionAdd>(func_fuse), 1);

    pass_manager.run_passes(func_nofuse1);
    ASSERT_EQ(count_ops_of_type<op::ConvolutionAdd>(func_nofuse1), 0);

    pass_manager.run_passes(func_nofuse2);
    ASSERT_EQ(count_ops_of_type<op::ConvolutionAdd>(func_nofuse2), 1);
}

TEST(cpu_fusion, conv_add)
{
    auto int_f = gen_conv_add(false, false);
    auto cpu_f = gen_conv_add(false, false);

    vector<vector<float>> args{{1.25f, 2.25f, 5.25f, 6.25f, -1.25f, -1.25f, 3.25f, -4.25f},
                               {-1.25f},
                               {1.25f, 2.25f, -3.25f, 2.25f, 4.25f, 4.25f, 1.25f, 2.25f}};

    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu_results.at(0), int_results.at(0)));

    int_f = gen_conv_add(false, true);
    cpu_f = gen_conv_add(false, true);

    int_results = execute(int_f, args, "INTERPRETER");
    cpu_results = execute(cpu_f, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu_results.at(0), int_results.at(0)));
}

1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
#if MKLDNN_VERSION_MAJOR < 1
static double gelu_backprop_factor(double x)
{
    auto pi = 4.0 * std::atan(1.0);
    return 0.5 * (1.0 + erf(x * sqrt(1.0 / 2.0))) + (x * exp(-x * x / 2.0)) / sqrt(2.0 * pi);
}

TEST(cpu_fusion, fuse_gelu_backprop_f32)
{
    Shape shape_a{2, 1, 60, 60};

    auto make_function = [shape_a]() {
        auto A = std::make_shared<op::Parameter>(element::f32, shape_a);
        auto gbpfactor = std::make_shared<op::GeluBackpropFactor>(A);
        auto delta = std::make_shared<op::Parameter>(element::f32, shape_a);
        auto gbp = gbpfactor * delta;

        auto f = make_shared<Function>(NodeVector{gbp}, ParameterVector{A, delta});
        return f;
    };
    auto fuse_func = make_function();
    // Test fusion
    {
        pass::Manager pass_manager;
        pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
        pass_manager.run_passes(fuse_func);
        ASSERT_EQ(count_ops_of_type<op::GeluBackprop>(fuse_func), 1);
    }

    // Test values
    {
        test::Uniform<float> rng(1.0f, 100.0f);
        vector<vector<float>> args;
        for (shared_ptr<op::Parameter> param : fuse_func->get_parameters())
        {
            auto name = param->get_name();
            vector<float> tensor_val(shape_size(param->get_shape()));
            rng.initialize(tensor_val);
            args.push_back(tensor_val);
        }

        auto backend = runtime::Backend::create("CPU");

        // Create some tensors for input/output
        auto a = backend->create_tensor(element::f32, shape_a);
        auto delta = backend->create_tensor(element::f32, shape_a);
        copy_data(a, args[0]);
        copy_data(delta, args[1]);
        auto result = backend->create_tensor(element::f32, shape_a);

        std::transform(args[0].begin(), args[0].end(), args[0].begin(), [](float x) -> float {
            return static_cast<float>(gelu_backprop_factor(static_cast<double>(x)));
        });

        std::transform(args[0].begin(),
                       args[0].end(),
                       args[1].begin(),
                       args[0].begin(),
                       [](float x, float delta) -> float { return static_cast<float>(x * delta); });

        auto handle = backend->compile(fuse_func);
        handle->call_with_validate({result}, {a, delta});
        EXPECT_TRUE(test::all_close(args[0], read_vector<float>(result), 0.007f, 0.007f));
    }
}
#endif

gaurides's avatar
gaurides committed
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
shared_ptr<Function> gen_deconv(const bool add_goe)
{
    Shape conv_out_shape{100, 64, 1, 1};
    auto out_delta = std::make_shared<op::Parameter>(element::f32, conv_out_shape);

    Shape filters_shape{64, 512, 4, 4};
    Shape bias_shape{512};
    Shape data_batch_shape{100, 512, 4, 4};

    auto data_label = std::make_shared<pattern::op::Label>(element::f32, data_batch_shape);
    auto filters = std::make_shared<op::Parameter>(element::f32, filters_shape);

    auto conv = std::make_shared<op::ConvolutionBackpropData>(data_label->get_shape(),
                                                              filters,
                                                              out_delta,
                                                              Strides{1, 1},
                                                              Strides{1, 1},
                                                              CoordinateDiff{0, 0},
                                                              CoordinateDiff{0, 0},
                                                              Strides{1, 1});
    auto conv_label = std::make_shared<pattern::op::Label>(conv, nullptr, NodeVector{conv});

    auto mean = std::make_shared<op::Parameter>(element::f32, bias_shape);
    auto var = std::make_shared<op::Parameter>(element::f32, bias_shape);
    auto gamma = std::make_shared<op::Parameter>(element::f32, bias_shape);
    auto beta = std::make_shared<op::Parameter>(element::f32, bias_shape);
    double eps = 0.001;

    auto goe_bn = std::make_shared<op::GetOutputElement>(conv, 0);

    // Adding a goe will stop fusion since the patterns wont expect to see this op
    auto bn = add_goe
                  ? std::make_shared<op::BatchNormInference>(goe_bn, gamma, beta, mean, var, eps)
                  : std::make_shared<op::BatchNormInference>(conv, gamma, beta, mean, var, eps);

    return make_shared<Function>(NodeVector{bn},
                                 ParameterVector{filters, out_delta, gamma, beta, mean, var});
}

TEST(cpu_fusion, fuse_deconv)
{
    bool use_deconv_fuse = (getenv("NGRAPH_DECONV_FUSE") != nullptr);
    if (!use_deconv_fuse)
    {
        set_environment("NGRAPH_DECONV_FUSE", "1", 1);
    }

    auto fuse_func = gen_deconv(false);
    auto nofuse_func = gen_deconv(true);

    {
        pass::Manager pass_manager;
        pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
        pass_manager.run_passes(fuse_func);
        ASSERT_EQ(count_ops_of_type<op::DeconvolutionBias>(fuse_func), 1);
    }

    {
        pass::Manager pass_manager;
        pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
        pass_manager.run_passes(nofuse_func);
        ASSERT_EQ(count_ops_of_type<op::DeconvolutionBias>(nofuse_func), 0);
        ASSERT_EQ(count_ops_of_type<op::Relu>(nofuse_func), 0);
    }

    // Test values
    {
        test::Uniform<float> rng(1.0f, 100.0f);
        vector<vector<float>> args;
        for (shared_ptr<op::Parameter> param : fuse_func->get_parameters())
        {
            auto name = param->get_name();
            vector<float> tensor_val(shape_size(param->get_shape()));
            rng.initialize(tensor_val);
            args.push_back(tensor_val);
        }
        auto nofuse_results = execute(nofuse_func, args, "CPU");
        auto fuse_results = execute(fuse_func, args, "CPU");

        EXPECT_TRUE(test::all_close(fuse_results.at(0), nofuse_results.at(0)));
    }

    if (!use_deconv_fuse)
    {
        unset_environment("NGRAPH_DECONV_FUSE");
    }
}

1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
shared_ptr<Function> gen_groupconv_batchnorm(const bool add_goe,
                                             const bool with_relu,
                                             const Shape shape_in,
                                             const Shape shape_weights,
                                             const Shape shape_out,
                                             const size_t groups)
{
    auto input = make_shared<op::Parameter>(element::f32, shape_in);
    auto weights = make_shared<op::Parameter>(element::f32, shape_weights);

    unsigned long OC = shape_out.at(1);
    Shape shape_bn{OC};
    auto group_conv = make_shared<op::GroupConvolution>(input,
                                                        weights,
                                                        Strides{1, 1},
                                                        Strides{1, 1},
                                                        CoordinateDiff{0, 0},
                                                        CoordinateDiff{0, 0},
                                                        Strides{1, 1},
1260
                                                        groups);
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271

    double eps = 0.001;
    auto gamma = std::make_shared<op::Parameter>(element::f32, shape_bn);
    auto beta = std::make_shared<op::Parameter>(element::f32, shape_bn);
    auto mean = std::make_shared<op::Parameter>(element::f32, shape_bn);
    auto var = std::make_shared<op::Parameter>(element::f32, shape_bn);

    auto goe_bn = std::make_shared<op::GetOutputElement>(group_conv, 0);

    // Adding a goe will stop fusion since the patterns wont expect to see this op
    auto bn =
1272 1273
        add_goe ? std::make_shared<op::BatchNormInference>(goe_bn, gamma, beta, mean, var, eps)
                : std::make_shared<op::BatchNormInference>(group_conv, gamma, beta, mean, var, eps);
1274 1275 1276 1277
    if (with_relu)
    {
        auto prelu = std::make_shared<op::Relu>(bn);
        auto f = make_shared<Function>(NodeVector{prelu},
1278
                                       ParameterVector{input, weights, gamma, beta, mean, var});
1279 1280 1281 1282 1283
        return f;
    }
    else
    {
        auto f = make_shared<Function>(NodeVector{bn},
1284
                                       ParameterVector{input, weights, gamma, beta, mean, var});
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 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
        return f;
    }
}

void fuse_groupconv_batchnorm_helper(Shape shape_in,
                                     Shape shape_weights,
                                     Shape shape_r,
                                     size_t groups)
{
    auto func_fuse =
        gen_groupconv_batchnorm(false, false, shape_in, shape_weights, shape_r, groups);
    auto func_fuse2 =
        gen_groupconv_batchnorm(false, true, shape_in, shape_weights, shape_r, groups);

    {
        pass::Manager pass_manager;
        pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
        pass_manager.run_passes(func_fuse);
        ASSERT_EQ(count_ops_of_type<op::GroupConvolutionBias>(func_fuse), 1);
    }

    {
        // test groupconv + batchnorm + relu fusion
        pass::Manager pass_manager;
        pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
        pass_manager.run_passes(func_fuse2);
        ASSERT_EQ(count_ops_of_type<op::GroupConvolutionBias>(func_fuse2), 1);
        ASSERT_EQ(count_ops_of_type<op::Relu>(func_fuse2), 0);
    }
}

void groupconv_batchnorm_test_val_helper(
    const bool with_relu, Shape shape_in, Shape shape_weights, Shape shape_r, size_t groups)
{
    shared_ptr<Function> fuse_func =
        gen_groupconv_batchnorm(false, with_relu, shape_in, shape_weights, shape_r, groups);
    shared_ptr<Function> nofuse_func =
        gen_groupconv_batchnorm(true, with_relu, shape_in, shape_weights, shape_r, groups);

    test::Uniform<float> rng(1.0f, 100.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : fuse_func->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    auto fuse_results = execute(fuse_func, args, "CPU");
    auto nofuse_results = execute(nofuse_func, args, "CPU");

    EXPECT_TRUE(test::all_close(fuse_results.at(0), nofuse_results.at(0)));
}

TEST(cpu_fusion, fuse_groupconv_batchnorm1)
{
    Shape shape_in{1, 20, 5, 5};
    Shape shape_weights{8, 10, 3, 3};
    Shape shape_r{1, 8, 3, 3};
    fuse_groupconv_batchnorm_helper(shape_in, shape_weights, shape_r, 2);
    groupconv_batchnorm_test_val_helper(false, shape_in, shape_weights, shape_r, 2);
    groupconv_batchnorm_test_val_helper(true, shape_in, shape_weights, shape_r, 2);
}

TEST(cpu_fusion, fuse_groupconv_batchnorm2)
{
    Shape shape_in{1, 20, 5, 5};
    Shape shape_weights{5, 4, 3, 3};
    Shape shape_r{1, 5, 3, 3};
    fuse_groupconv_batchnorm_helper(shape_in, shape_weights, shape_r, 5);
    groupconv_batchnorm_test_val_helper(false, shape_in, shape_weights, shape_r, 5);
    groupconv_batchnorm_test_val_helper(true, shape_in, shape_weights, shape_r, 5);
}

TEST(cpu_fusion, fuse_groupconv_batchnorm3)
{
    Shape shape_in{1, 20, 5, 5};
    Shape shape_weights{20, 1, 3, 3};
    Shape shape_r{1, 20, 3, 3};
    fuse_groupconv_batchnorm_helper(shape_in, shape_weights, shape_r, 20);
    groupconv_batchnorm_test_val_helper(false, shape_in, shape_weights, shape_r, 20);
    groupconv_batchnorm_test_val_helper(true, shape_in, shape_weights, shape_r, 20);
}

TEST(cpu_fusion, fuse_groupconv_batchnorm4)
{
    Shape shape_in{1, 20, 4, 4};
    Shape shape_weights{5, 20, 1, 1};
    Shape shape_r{1, 5, 4, 4};
    fuse_groupconv_batchnorm_helper(shape_in, shape_weights, shape_r, 1);
    groupconv_batchnorm_test_val_helper(false, shape_in, shape_weights, shape_r, 1);
    groupconv_batchnorm_test_val_helper(true, shape_in, shape_weights, shape_r, 1);
}

1379 1380 1381 1382 1383 1384 1385 1386
std::vector<shared_ptr<runtime::Tensor>> rnn_matrix_fusion_eval(const size_t time_steps,
                                                                const Shape& data_shape,
                                                                const Shape& weights_shape,
                                                                const Shape& bias_shape,
                                                                const vector<float>& data_val,
                                                                const vector<float>& weights_val,
                                                                const vector<float>& bias_val,
                                                                const bool enable_pass)
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
{
    auto data = make_shared<op::Parameter>(element::f32, data_shape);
    auto weights = make_shared<op::Parameter>(element::f32, weights_shape);
    auto bias = make_shared<op::Parameter>(element::f32, bias_shape);

    // results from each time step
    NodeVector results;
    for (size_t t = 0; t < time_steps; ++t)
    {
        auto data_slice = make_shared<op::Slice>(
            data, Coordinate{0, t, 0}, Coordinate{data_shape[0], t + 1, data_shape[2]});
        auto data_reshape = make_shared<op::Reshape>(
            data_slice, AxisVector{0, 1, 2}, Shape{data_shape[0], data_shape[2]});
        auto weights_reshape = make_shared<op::Reshape>(
            weights, AxisVector{1, 0}, Shape{weights_shape[1], weights_shape[0]});
        auto dot = make_shared<op::Dot>(data_reshape, weights_reshape);
        auto bias_broadcast = make_shared<op::Broadcast>(bias, dot->get_shape(), AxisSet{0});
        auto add = make_shared<op::Add>(dot, bias_broadcast);
        results.push_back(add);
    }
1407
    auto func = make_shared<Function>(results, ParameterVector{data, weights, bias});
1408 1409 1410 1411
    if (enable_pass)
    {
        pass::Manager pass_manager;
        pass_manager.register_pass<runtime::cpu::pass::CPURnnMatFusion>();
1412 1413
        pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(
            pass::FusionType::REGULAR_FUSIONS);
1414 1415 1416 1417 1418 1419
        pass_manager.run_passes(func);
        // check all of our dot/add are converted to a single MatmulBias op.
        size_t count = count_ops_of_type<op::MatmulBias>(func);
        EXPECT_EQ(count, 1);
    }

1420
    auto backend = runtime::Backend::create("CPU");
1421

1422
    shared_ptr<runtime::Tensor> data_tensor =
1423
        backend->create_tensor(element::f32, data->get_shape());
1424
    shared_ptr<runtime::Tensor> weights_tensor =
1425
        backend->create_tensor(element::f32, weights->get_shape());
1426
    shared_ptr<runtime::Tensor> bias_tensor =
1427
        backend->create_tensor(element::f32, bias->get_shape());
1428

1429
    std::vector<shared_ptr<runtime::Tensor>> result_tensors;
1430 1431
    for (auto r : results)
    {
1432
        result_tensors.push_back(backend->create_tensor(element::f32, r->get_shape()));
1433 1434 1435 1436 1437
    }

    copy_data(data_tensor, data_val);
    copy_data(weights_tensor, weights_val);
    copy_data(bias_tensor, bias_val);
1438 1439
    auto handle = backend->compile(func);
    handle->call_with_validate(result_tensors, {data_tensor, weights_tensor, bias_tensor});
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
    return result_tensors;
}

TEST(cpu_fusion, rnn_matrix_fusion_eval_pass)
{
    const size_t time_steps = 4;
    Shape data_shape{3, time_steps, 5};
    Shape weights_shape{6, data_shape[2]};
    Shape bias_shape{6};

    test::Uniform<float> rng{0, 1, 0};
    vector<float> data_val(shape_size(data_shape));
    vector<float> weights_val(shape_size(weights_shape));
    vector<float> bias_val(shape_size(bias_shape));
    rng.initialize(data_val);
    rng.initialize(weights_val);
    rng.initialize(bias_val);

1458
    std::vector<shared_ptr<runtime::Tensor>> result_expected = rnn_matrix_fusion_eval(
1459
        time_steps, data_shape, weights_shape, bias_shape, data_val, weights_val, bias_val, false);
1460
    std::vector<shared_ptr<runtime::Tensor>> result_fused = rnn_matrix_fusion_eval(
1461 1462 1463 1464 1465 1466
        time_steps, data_shape, weights_shape, bias_shape, data_val, weights_val, bias_val, true);
    for (size_t i = 0; i < result_expected.size(); ++i)
    {
        EXPECT_TRUE(test::all_close<float>(result_expected[i], result_fused[i]));
    }
}
1467

Nick Korovaiko's avatar
Nick Korovaiko committed
1468 1469 1470 1471 1472 1473
TEST(cpu_fusion, weight_fusion)
{
    auto param = std::make_shared<op::Parameter>(element::f32, Shape{64});
    auto reshape_conv =
        std::make_shared<ngraph::op::Reshape>(param, AxisVector{0}, Shape{16, 4, 1, 1});
    auto data_conv = std::make_shared<op::Parameter>(element::f32, Shape{16, 4, 7, 7});
1474
    auto tvt = &reshape_conv->output(0).get_tensor();
1475
    auto lt_desc = std::make_shared<runtime::cpu::LayoutDescriptor>(*tvt);
Nick Korovaiko's avatar
Nick Korovaiko committed
1476 1477 1478 1479 1480 1481 1482
    auto cvt_lt_conv = std::make_shared<runtime::cpu::op::ConvertLayout>(reshape_conv, lt_desc);
    auto conv = std::make_shared<ngraph::op::Convolution>(
        data_conv, cvt_lt_conv, Strides{1, 1}, Strides{1, 1});

    auto reshape_conv_bprop =
        std::make_shared<op::Reshape>(param, AxisVector{0}, Shape{16, 4, 1, 1});
    auto dummy_arg_conv_bprop = std::make_shared<op::Parameter>(element::f32, Shape{1, 16, 7, 7});
1483
    auto tvt_bprop = &reshape_conv_bprop->output(0).get_tensor();
1484
    auto lt_desc_bprop = std::make_shared<runtime::cpu::LayoutDescriptor>(*tvt_bprop);
Nick Korovaiko's avatar
Nick Korovaiko committed
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
    auto cvt_lt_conv_bprop =
        std::make_shared<runtime::cpu::op::ConvertLayout>(reshape_conv_bprop, lt_desc_bprop);
    auto conv_bprop = std::make_shared<op::ConvolutionBackpropData>(Shape{1, 4, 7, 7},
                                                                    cvt_lt_conv_bprop,
                                                                    dummy_arg_conv_bprop,
                                                                    Strides{1, 1},
                                                                    Strides{1, 1},
                                                                    CoordinateDiff{0, 0},
                                                                    CoordinateDiff{0, 0},
                                                                    Strides{1, 1});

    auto conv_relu = std::make_shared<op::Relu>(conv);
    auto conv_bprop_abs = std::make_shared<op::Abs>(conv_bprop);

    auto f = make_shared<Function>(NodeVector{conv_relu, conv_bprop_abs},
1500
                                   ParameterVector{param, data_conv, dummy_arg_conv_bprop});
Nick Korovaiko's avatar
Nick Korovaiko committed
1501 1502 1503 1504 1505 1506 1507 1508

    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUPostLayoutOptimizations>();
    pass_manager.run_passes(f);

    auto new_conv_bprop_data = conv_bprop_abs->get_argument(0);
    auto new_convert_layout = new_conv_bprop_data->get_argument(0);

1509
    ASSERT_EQ(as_type_ptr<runtime::cpu::op::ConvertLayout>(new_convert_layout->get_argument(0)),
Nick Korovaiko's avatar
Nick Korovaiko committed
1510 1511
              cvt_lt_conv);
}
1512 1513 1514 1515 1516 1517 1518 1519 1520

TEST(cpu_fusion, max_pool_with_indices)
{
    Shape shape_a{10, 3, 28, 28};
    auto input = std::make_shared<op::Parameter>(element::f32, shape_a);
    Shape window_shape{2, 2};
    auto max_pool = std::make_shared<op::MaxPool>(input, window_shape);
    auto C = std::make_shared<op::Parameter>(element::f32, max_pool->get_shape());

1521
    ngraph::autodiff::Adjoints adjoints(ngraph::OutputVector{max_pool}, ngraph::OutputVector{C});
1522 1523 1524

    auto dinput = adjoints.backprop_node(input);

1525
    auto df = std::make_shared<Function>(NodeVector{dinput}, ParameterVector{input, C});
1526

1527
    auto f = std::make_shared<Function>(NodeVector{max_pool}, ParameterVector{input});
1528 1529

    {
1530
        NodeVector nv_cwi;
1531
        pass::Manager pass_manager;
1532
        pass_manager.register_pass<runtime::cpu::pass::CPUWorkspaceInsertion>(nv_cwi);
1533 1534 1535 1536
        pass_manager.run_passes(df);
    }

    auto maxpool_goe_output =
1537
        as_type_ptr<op::GetOutputElement>(f->get_results().at(0)->get_argument(0));
1538 1539 1540 1541
    ASSERT_TRUE(maxpool_goe_output);
    ASSERT_EQ(maxpool_goe_output->get_n(), 0);
    auto maxpool_with_indices = df->get_results().at(0)->get_argument(0);
    auto maxpool_goe_indices =
1542
        as_type_ptr<op::GetOutputElement>(maxpool_with_indices->get_argument(2));
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
    ASSERT_TRUE(maxpool_goe_indices);
    ASSERT_EQ(maxpool_goe_indices->get_n(), 1);
}

TEST(cpu_fusion, backwards_maxpool_with_indices_n4_c1_hw4_2x2_max)
{
    Shape shape_a{1, 4, 4, 4};
    Shape maxpool_shape{1, 4, 3, 3};
    auto A = std::make_shared<op::Parameter>(element::f32, shape_a);
    Shape window_shape{2, 2};
    auto window_movement_strides = Strides{1, 1};
    auto maxpool = std::make_shared<op::MaxPool>(A, window_shape, window_movement_strides);
1555
    auto f = std::make_shared<Function>(maxpool, ParameterVector{A});
1556 1557

    auto backend = runtime::Backend::create("CPU");
1558
    shared_ptr<runtime::Tensor> ep = backend->create_tensor(element::f32, maxpool_shape);
1559 1560
    vector<float> dataEp(shape_size(maxpool_shape), 4);

1561 1562
    shared_ptr<runtime::Tensor> input = backend->create_tensor(element::f32, shape_a);
    shared_ptr<runtime::Tensor> output = backend->create_tensor(element::f32, shape_a);
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584

    vector<float> dataInput{11.f, 31.f, 40.f, 47.f, 13.f, 61.f, 48.f, 59.f, 17.f, 39.f, 64.f,
                            62.f, 45.f, 55.f, 36.f, 19.f, 65.f, 33.f, 49.f, 30.f, 56.f, 41.f,
                            53.f, 58.f, 22.f, 35.f, 52.f, 50.f, 63.f, 54.f, 12.f, 26.f, 44.f,
                            21.f, 69.f, 24.f, 46.f, 25.f, 51.f, 29.f, 72.f, 15.f, 73.f, 10.f,
                            16.f, 37.f, 70.f, 32.f, 28.f, 66.f, 57.f, 27.f, 60.f, 42.f, 43.f,
                            71.f, 18.f, 38.f, 67.f, 68.f, 14.f, 20.f, 34.f, 23.f};

    vector<float> expected{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 12.0f, 0.0f, 4.0f, 0.0f, 0.0f,  16.0f,
                           0.0f, 0.0f, 4.0f, 0.0f, 0.0f, 4.0f,  0.0f, 0.0f, 0.0f, 4.0f,  0.0f,
                           8.0f, 8.0f, 0.0f, 0.0f, 4.0f, 0.0f,  4.0f, 4.0f, 0.0f, 0.0f,  0.0f,
                           0.0f, 8.0f, 0.0f, 4.0f, 0.0f, 0.0f,  0.0f, 8.0f, 0.0f, 16.0f, 0.0f,
                           0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 8.0f,  0.0f, 0.0f, 4.0f, 0.0f,  0.0f,
                           8.0f, 0.0f, 4.0f, 8.0f, 4.0f, 0.0f,  0.0f, 0.0f, 0.0f};

    copy_data(ep, dataEp);
    copy_data(input, dataInput);

    auto C = std::make_shared<op::Parameter>(element::f32, maxpool_shape);
    auto df = autodiff::backprop_function(f);

    {
1585
        NodeVector nv_cwi;
1586
        pass::Manager pass_manager;
1587
        pass_manager.register_pass<pass::VisualizeTree>("max_pool_bprop_before2.png");
1588
        pass_manager.register_pass<runtime::cpu::pass::CPUWorkspaceInsertion>(nv_cwi);
1589
        pass_manager.register_pass<pass::VisualizeTree>("max_pool_bprop_after2.png");
1590 1591 1592
        pass_manager.run_passes(df);
    }

1593
    auto handle = backend->compile(df);
1594
    handle->call_with_validate({output}, {input, ep});
1595
    EXPECT_TRUE(test::all_close_f(read_vector<float>(output), expected, MIN_FLOAT_TOLERANCE_BITS));
1596
}
1597

1598 1599 1600 1601 1602 1603 1604 1605
static std::shared_ptr<ngraph::Function> make_forward_function()
{
    Shape shape_a{10, 3, 28, 28};
    auto input = std::make_shared<op::Parameter>(element::f32, shape_a);
    Shape window_shape{2, 2};
    auto max_pool = std::make_shared<op::MaxPool>(input, window_shape);
    auto neg = std::make_shared<op::Negative>(max_pool);
    auto absn = std::make_shared<op::Abs>(max_pool);
1606
    return std::make_shared<Function>(NodeVector{max_pool, neg, absn}, ParameterVector{input});
1607 1608
}

1609
static std::pair<std::shared_ptr<ngraph::Function>, OutputVector>
1610 1611 1612 1613 1614
    make_backward_function(std::shared_ptr<ngraph::Function> f)
{
    // get parameters
    std::vector<std::shared_ptr<ngraph::op::Parameter>> back_parameters = f->get_parameters();

1615 1616
    ngraph::OutputVector adjoints;
    ngraph::OutputVector outputs;
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
    for (auto Y : f->get_results())
    {
        // Get the output
        // Create the Adjoint
        auto C = std::make_shared<ngraph::op::Parameter>(Y->get_element_type(), Y->get_shape());
        outputs.push_back(Y);
        adjoints.push_back(C);
    }

    ngraph::autodiff::Adjoints adjoint{outputs, adjoints};

    // Perform autodiff
1629
    OutputVector dYdXs(back_parameters.size());
1630 1631 1632 1633 1634 1635 1636 1637
    transform(back_parameters.begin(),
              back_parameters.end(),
              dYdXs.begin(),
              [&adjoint](const std::shared_ptr<Node>& X) { return adjoint.backprop_node(X); });

    // create the backward function
    std::vector<std::shared_ptr<ngraph::op::Parameter>> param_adjoints;
    for (auto n : adjoints)
1638
        param_adjoints.push_back(as_type_ptr<ngraph::op::Parameter>(n.get_node_shared_ptr()));
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
    back_parameters.insert(back_parameters.begin(), param_adjoints.begin(), param_adjoints.end());

    return {std::make_shared<ngraph::Function>(dYdXs, back_parameters), adjoints};
}

void optimize_graph(std::shared_ptr<ngraph::Function>& f, std::shared_ptr<ngraph::Function> bf)
{
    // start by removing excess reshapes
    NodeVector nv_cwi;
    ngraph::pass::Manager pass_manager;
    pass_manager.register_pass<ngraph::pass::ReshapeElimination>();
    pass_manager.register_pass<ngraph::pass::ReshapeElimination>();
    pass_manager.register_pass<runtime::cpu::pass::CPUWorkspaceInsertion>(nv_cwi);
1652
    pass_manager.register_pass<pass::VisualizeTree>("before.fprop_cache.png");
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702

    pass_manager.run_passes(f);
    pass_manager.run_passes(bf);
    if (nv_cwi.size() > 0)
    {
        NodeVector new_outputs;
        for (auto r : f->get_results())
        {
            new_outputs.push_back(r->get_argument(0));
        }

        new_outputs.insert(new_outputs.end(), nv_cwi.begin(), nv_cwi.end());
        f = std::make_shared<ngraph::Function>(new_outputs, f->get_parameters());
    }

    ngraph::NodeVector dYdXs;
    for (size_t i = 0; i < bf->get_output_size(); ++i)
    {
        dYdXs.push_back(bf->get_output_op(i)->get_argument(0));
    }

    ngraph::NodeVector combined_outputs;
    for (auto r : f->get_results())
    {
        combined_outputs.push_back(r->get_argument(0));
    }

    combined_outputs.insert(combined_outputs.end(), dYdXs.begin(), dYdXs.end());

    std::vector<std::shared_ptr<ngraph::op::Parameter>> combined_parameters = f->get_parameters();
    std::vector<std::shared_ptr<ngraph::op::Parameter>> back_parameters = bf->get_parameters();

    combined_parameters.insert(
        combined_parameters.end(), back_parameters.begin(), back_parameters.end());
    auto combinedf = std::make_shared<ngraph::Function>(combined_outputs, combined_parameters);
    // rerun Reshape elimination to help simplify the graph again, run CPUFusion
    // this replaces nodes in both f and bf due to shared-ptr - ness
    ngraph::pass::Manager pass_manager_comb;
    pass_manager_comb.register_pass<ngraph::pass::ReshapeElimination>();
    pass_manager_comb.register_pass<ngraph::runtime::cpu::pass::CPUFusion>();
    pass_manager_comb.run_passes(combinedf);
}

TEST(cpu_fusion, maxpool_with_indices_in_mxnet)
{
    auto f = make_forward_function();
    auto bfa = make_backward_function(f);
    auto maybe_bf = bfa.first;
    auto adjoints = bfa.second;
    optimize_graph(f, maybe_bf);
1703
    auto fprop_cache = ngraph::cache_fprop(f, maybe_bf);
1704 1705

    auto mpwi_bprop = fprop_cache.bprop->get_results().at(0)->get_argument(0);
1706 1707
    ASSERT_TRUE(as_type_ptr<op::Parameter>(mpwi_bprop->get_argument(0)));
    ASSERT_TRUE(as_type_ptr<op::Parameter>(mpwi_bprop->get_argument(2)));
1708 1709
}

1710
TEST(cpu_fusion, conv_batch_norm_folding)
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
{
    Shape shape_input{1, 8, 3, 3};
    Shape shape_weights{2, 8, 1, 1};
    Shape shape_norm{2};

    auto make_function = [shape_input, shape_weights, shape_norm]() {
        auto input = std::make_shared<op::Parameter>(element::f32, shape_input);
        auto weights = std::make_shared<op::Parameter>(element::f32, shape_weights);
        double eps = 0.001;
        auto gamma = std::make_shared<op::Parameter>(element::f32, shape_norm);
        auto beta = std::make_shared<op::Parameter>(element::f32, shape_norm);
        auto mean = std::make_shared<op::Parameter>(element::f32, shape_norm);
        auto var = std::make_shared<op::Parameter>(element::f32, shape_norm);
        auto conv = std::make_shared<op::Convolution>(input, weights, Strides{1, 1}, Strides{1, 1});
1725
        auto bn = std::make_shared<op::BatchNormInference>(conv, gamma, beta, mean, var, eps);
1726
        auto f = make_shared<Function>(NodeVector{bn},
1727
                                       ParameterVector{input, weights, gamma, beta, mean, var});
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
        return f;
    };

    auto int_f = make_function();
    auto cpu_f = make_function();

    vector<vector<float>> args{
        {1.25f,  2.25f, 5.25f, 6.25f,  -1.25f, -1.25f, 3.25f, -4.25f, 7.25f,  8.25f,  -1.25f,
         -1.25f, 1.25f, 2.25f, -3.25f, 2.25f,  4.25f,  4.25f, 1.25f,  2.25f,  -4.25f, 2.25f,
         4.25f,  4.25f, 0.f,   0.f,    -1.f,   0.f,    2.f,   2.f,    0.f,    0.f,    0.f,
         0.f,    2.f,   2.f,   1.25f,  2.25f,  5.25f,  6.25f, 1.25f,  1.25f,  3.25f,  4.25f,
         -7.25f, 8.25f, 1.25f, -1.25f, -1.25f, 2.25f,  3.25f, 2.25f,  -4.25f, -4.25f, -1.25f,
         -2.25f, 4.25f, 2.25f, 4.25f,  4.25f,  0.f,    0.f,   1.f,    0.f,    -2.f,   2.f,
         0.f,    0.f,   0.f,   0.f,    -2.f,   -2.f},
        {1.25f,
         2.25f,
         5.25f,
         6.25f,
         -1.25f,
         -1.25f,
         3.25f,
         -4.25f,
         7.25f,
         8.25f,
         -1.25f,
         0.f,
         0.f,
         0.f,
         0.f,
         -2.f},
        {-0.9384f, 0.01875f},
        {11.0f, 1.3f},
        {0.12f, 0.31f},
        {0.01f, 0.11f},
    };

    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu_results.at(0), int_results.at(0)));
}
1768

1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
TEST(cpu_fusion, convbias_batch_norm_folding)
{
    Shape shape_input{2, 8, 5, 5};
    Shape shape_weights{2, 8, 2, 2};
    Shape shape_norm{2};

    auto make_function = [shape_input, shape_weights, shape_norm]() {
        auto input = std::make_shared<op::Parameter>(element::f32, shape_input);
        auto weights = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto bias = std::make_shared<op::Parameter>(element::f32, Shape{2});
        double eps = 1.01;
        auto gamma = std::make_shared<op::Parameter>(element::f32, shape_norm);
        auto beta = std::make_shared<op::Parameter>(element::f32, shape_norm);
        auto mean = std::make_shared<op::Parameter>(element::f32, shape_norm);
        auto var = std::make_shared<op::Parameter>(element::f32, shape_norm);
        auto conv = std::make_shared<op::Convolution>(input, weights, Strides{1, 1}, Strides{1, 1});
        auto convbias =
            conv + std::make_shared<op::Broadcast>(bias, conv->get_shape(), AxisSet{0, 2, 3});
1787
        auto bn = std::make_shared<op::BatchNormInference>(convbias, gamma, beta, mean, var, eps);
1788
        auto f = make_shared<Function>(
1789
            NodeVector{bn}, ParameterVector{input, weights, bias, gamma, beta, mean, var});
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
        return f;
    };

    auto int_f = make_function();
    auto cpu_f = make_function();

    test::Uniform<float> rng(1.0f, 100.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : cpu_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu_results.at(0), int_results.at(0)));
}

TEST(cpu_fusion, conv_affine_folding)
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
{
    Shape shape_input{1, 8, 3, 3};
    Shape shape_weights{2, 8, 1, 1};
    Shape shape_norm{2};

    auto make_function = [shape_input, shape_weights, shape_norm]() {
        auto input = std::make_shared<op::Parameter>(element::f32, shape_input);
        auto weights = std::make_shared<op::Parameter>(element::f32, shape_weights);

        auto a = std::make_shared<op::Parameter>(element::f32, shape_norm);
        auto b = std::make_shared<op::Parameter>(element::f32, shape_norm);
        auto conv = std::make_shared<op::Convolution>(input, weights, Strides{1, 1}, Strides{1, 1});
        auto out = std::make_shared<op::Add>(
            std::make_shared<op::Multiply>(
                conv, std::make_shared<op::Broadcast>(a, conv->get_shape(), AxisSet{0, 2, 3})),
            std::make_shared<op::Broadcast>(b, conv->get_shape(), AxisSet{0, 2, 3}));
1827
        auto f = make_shared<Function>(NodeVector{out}, ParameterVector{input, weights, a, b});
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
        return f;
    };

    auto int_f = make_function();
    auto cpu_f = make_function();

    vector<vector<float>> args{
        {1.25f,  2.25f, 5.25f, 6.25f,  -1.25f, -1.25f, 3.25f, -4.25f, 7.25f,  8.25f,  -1.25f,
         -1.25f, 1.25f, 2.25f, -3.25f, 2.25f,  4.25f,  4.25f, 1.25f,  2.25f,  -4.25f, 2.25f,
         4.25f,  4.25f, 0.f,   0.f,    -1.f,   0.f,    2.f,   2.f,    0.f,    0.f,    0.f,
         0.f,    2.f,   2.f,   1.25f,  2.25f,  5.25f,  6.25f, 1.25f,  1.25f,  3.25f,  4.25f,
         -7.25f, 8.25f, 1.25f, -1.25f, -1.25f, 2.25f,  3.25f, 2.25f,  -4.25f, -4.25f, -1.25f,
         -2.25f, 4.25f, 2.25f, 4.25f,  4.25f,  0.f,    0.f,   1.f,    0.f,    -2.f,   2.f,
         0.f,    0.f,   0.f,   0.f,    -2.f,   -2.f},
        {1.25f,
         2.25f,
         5.25f,
         6.25f,
         -1.25f,
         -1.25f,
         3.25f,
         -4.25f,
         7.25f,
         8.25f,
         -1.25f,
         0.f,
         0.f,
         0.f,
         0.f,
         -2.f},
        {-0.9384f, 0.01875f},
        {11.0f, 1.3f},
    };

    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu_results.at(0), int_results.at(0)));
}

1867
TEST(cpu_fusion, convbias_affine_folding1)
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
{
    Shape shape_input{1, 6, 3, 3};
    Shape shape_weights{3, 6, 1, 1};
    Shape shape_norm{3};

    auto make_function = [shape_input, shape_weights, shape_norm]() {
        auto input = std::make_shared<op::Parameter>(element::f32, shape_input);
        auto weights = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto bias = std::make_shared<op::Parameter>(element::f32, Shape{3});

        auto a = std::make_shared<op::Parameter>(element::f32, shape_norm);
        auto b = std::make_shared<op::Parameter>(element::f32, shape_norm);
        auto conv = std::make_shared<op::Convolution>(input, weights, Strides{1, 1}, Strides{1, 1});
        auto convbias =
            conv + std::make_shared<op::Broadcast>(bias, conv->get_shape(), AxisSet{0, 2, 3});
        auto out = std::make_shared<op::Add>(
            std::make_shared<op::Multiply>(
                convbias, std::make_shared<op::Broadcast>(a, conv->get_shape(), AxisSet{0, 2, 3})),
            std::make_shared<op::Broadcast>(b, conv->get_shape(), AxisSet{0, 2, 3}));
        auto f =
1888
            make_shared<Function>(NodeVector{out}, ParameterVector{input, weights, bias, a, b});
1889 1890 1891
        return f;
    };

1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
    auto func = make_function();
    pass_manager.run_passes(func);
    ASSERT_EQ(count_ops_of_type<op::ConvolutionBiasAdd>(func), 1);

    auto int_f = make_function();
    auto cpu_f = make_function();

    test::Uniform<float> rng(20.0f, 300.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : cpu_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu_results.at(0), int_results.at(0)));
}

TEST(cpu_fusion, convbias_affine_folding2)
{
    Shape shape_input{1, 6, 3, 3};
    Shape shape_weights{3, 6, 1, 1};
    Shape shape_norm{1};

    auto make_function = [shape_input, shape_weights, shape_norm]() {
        auto input = std::make_shared<op::Parameter>(element::f32, shape_input);
        auto weights = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto bias = std::make_shared<op::Parameter>(element::f32, Shape{3});

        auto a = std::make_shared<op::Parameter>(element::f32, shape_norm);
        auto b = std::make_shared<op::Parameter>(element::f32, shape_norm);
        auto conv = std::make_shared<op::Convolution>(input, weights, Strides{1, 1}, Strides{1, 1});
        auto convbias =
            conv + std::make_shared<op::Broadcast>(bias, conv->get_shape(), AxisSet{0, 2, 3});
        auto out = std::make_shared<op::Add>(
            std::make_shared<op::Multiply>(
                convbias, std::make_shared<op::Broadcast>(a, conv->get_shape(), AxisSet{1, 2, 3})),
            std::make_shared<op::Broadcast>(b, conv->get_shape(), AxisSet{1, 2, 3}));
        auto f =
            make_shared<Function>(NodeVector{out}, ParameterVector{input, weights, bias, a, b});
        return f;
    };

    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
    auto func = make_function();
    pass_manager.run_passes(func);
    ASSERT_EQ(count_ops_of_type<op::ConvolutionBiasAdd>(func), 1);

1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
    auto int_f = make_function();
    auto cpu_f = make_function();

    test::Uniform<float> rng(20.0f, 300.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : cpu_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu_results.at(0), int_results.at(0)));
}

1963
TEST(batch_fusion, group_convolution)
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
{
    auto backend = runtime::Backend::create("CPU");
    test::Uniform<float> rng(2.0f, 10.0f);

    const size_t GROUPS = 2;
    Shape shape_a{1, 32, 2, 2};
    auto A = make_shared<op::Parameter>(element::f32, shape_a);
    Shape shape_b{2, 16, 1, 1};
    auto B = make_shared<op::Parameter>(element::f32, shape_b);
    Shape shape_r{1, 2, 2, 2};
    auto group_conv = make_shared<op::GroupConvolution>(A,
                                                        B,
                                                        Strides{1, 1},
                                                        Strides{1, 1},
                                                        CoordinateDiff{0, 0},
                                                        CoordinateDiff{0, 0},
                                                        Strides{1, 1},
1981
                                                        GROUPS);
1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005

    Shape shape_c{1, 16, 2, 2};
    auto C = make_shared<op::Parameter>(element::f32, shape_c);
    Shape shape_d{1, 16, 1, 1};
    auto D = make_shared<op::Parameter>(element::f32, shape_d);
    auto conv_lower = make_shared<op::Convolution>(C,
                                                   D,
                                                   Strides{1, 1},
                                                   Strides{1, 1},
                                                   CoordinateDiff{0, 0},
                                                   CoordinateDiff{0, 0},
                                                   Strides{1, 1});

    auto E = make_shared<op::Parameter>(element::f32, shape_c);
    auto F = make_shared<op::Parameter>(element::f32, shape_d);
    auto conv_upper = make_shared<op::Convolution>(E,
                                                   F,
                                                   Strides{1, 1},
                                                   Strides{1, 1},
                                                   CoordinateDiff{0, 0},
                                                   CoordinateDiff{0, 0},
                                                   Strides{1, 1});

    auto f = make_shared<Function>(NodeVector{group_conv, conv_lower, conv_upper},
2006
                                   ParameterVector{A, B, C, D, E, F});
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016

    auto a_ = rng.initialize(backend->create_tensor(element::f32, shape_a));
    auto b_ = rng.initialize(backend->create_tensor(element::f32, shape_b));

    vector<float> rv(shape_size(shape_r), 0);
    auto group_result = std::dynamic_pointer_cast<ngraph::runtime::cpu::CPUTensorView>(
        backend->create_tensor(element::f32, shape_r, rv.data()));

    auto av = read_vector<float>(a_);
    auto bv = read_vector<float>(b_);
2017 2018
    auto c_ = backend->create_tensor(element::f32, shape_c, av.data()); // lower data
    auto d_ = backend->create_tensor(element::f32, shape_d, bv.data()); // upper data
2019 2020

    auto e_ =
2021
        backend->create_tensor(element::f32, shape_c, av.data() + av.size() / 2); // lower weights
2022
    auto f_ =
2023
        backend->create_tensor(element::f32, shape_d, bv.data() + bv.size() / 2); // upper weights
2024 2025

    Shape shape_ur{1, 1, 2, 2};
2026
    // allocate a contigious storage for both lower and upper halves.
2027 2028 2029 2030 2031
    vector<float> erv(shape_size(shape_r), 0);
    auto lower_result = std::dynamic_pointer_cast<ngraph::runtime::cpu::CPUTensorView>(
        backend->create_tensor(element::f32, shape_ur, erv.data()));
    auto upper_result = std::dynamic_pointer_cast<ngraph::runtime::cpu::CPUTensorView>(
        backend->create_tensor(element::f32, shape_ur, erv.data() + erv.size() / 2));
2032 2033 2034
    auto handle = backend->compile(f);
    handle->call_with_validate({group_result, lower_result, upper_result},
                               {a_, b_, c_, d_, e_, f_});
2035
    EXPECT_TRUE(test::all_close_f(rv, erv));
2036 2037
}

2038
#if MKLDNN_VERSION_MAJOR < 1
2039 2040 2041 2042
TEST(cpu_fusion, rnn_fprop_1_lstm_cell)
{
    auto src_layer = make_shared<op::Parameter>(element::f32, Shape{10, 100});
    auto src_iter = make_shared<op::Parameter>(element::f32, Shape{20, 100});
2043 2044
    auto weights_layer = make_shared<op::Parameter>(element::f32, Shape{100, 400});
    auto weights_iter = make_shared<op::Parameter>(element::f32, Shape{100, 400});
2045 2046 2047 2048 2049 2050 2051
    auto biases = make_shared<op::Parameter>(element::f32, Shape{400});
    const int number_of_timesteps = 1;
    const int number_of_gates_per_cell = 4;
    const int src_seq_length = 1;
    const int num_rnn_cell_states = 2;
    const int rnn_direction = 1;
    const int num_of_rnn_fused_layer = 1;
Pruthvi's avatar
Pruthvi committed
2052 2053 2054
    ngraph::runtime::cpu::rnn_utils::rnntype rnn_type =
        ngraph::runtime::cpu::rnn_utils::rnntype::vanilla_lstm;

2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
    auto rnn_node = make_shared<op::Rnn>(src_layer,
                                         src_iter,
                                         weights_layer,
                                         weights_iter,
                                         biases,
                                         number_of_timesteps,
                                         number_of_gates_per_cell,
                                         src_seq_length,
                                         num_rnn_cell_states,
                                         rnn_direction,
Pruthvi's avatar
Pruthvi committed
2065 2066 2067
                                         num_of_rnn_fused_layer,
                                         rnn_type);

2068 2069 2070 2071 2072
    auto rnn_ht_output = make_shared<op::GetOutputElement>(rnn_node, 0);
    auto rnn_ct_output = make_shared<op::GetOutputElement>(rnn_node, 1);

    auto func = make_shared<Function>(
        NodeVector{rnn_ht_output, rnn_ct_output},
2073
        ParameterVector{src_layer, src_iter, weights_layer, weights_iter, biases});
2074 2075
    auto backend = runtime::Backend::create("CPU");

2076
    shared_ptr<runtime::Tensor> src_layer_t =
2077
        backend->create_tensor(element::f32, src_layer->get_shape());
2078
    shared_ptr<runtime::Tensor> src_iter_t =
2079
        backend->create_tensor(element::f32, src_iter->get_shape());
2080
    shared_ptr<runtime::Tensor> weights_layer_t =
2081
        backend->create_tensor(element::f32, weights_layer->get_shape());
2082
    shared_ptr<runtime::Tensor> weights_iter_t =
2083
        backend->create_tensor(element::f32, weights_iter->get_shape());
2084
    shared_ptr<runtime::Tensor> biases_t =
2085
        backend->create_tensor(element::f32, biases->get_shape());
2086
    shared_ptr<runtime::Tensor> result_ht = backend->create_tensor(element::f32, {10, 100});
2087
    shared_ptr<runtime::Tensor> result_ct = backend->create_tensor(element::f32, Shape{20, 100});
2088 2089 2090 2091 2092 2093 2094

    copy_data(src_layer_t, vector<float>(1000, 1));
    copy_data(src_iter_t, vector<float>(2000, 1));
    copy_data(weights_layer_t, vector<float>(400 * 100, 1));
    copy_data(weights_iter_t, vector<float>(400 * 100, 1));
    copy_data(biases_t, vector<float>(400, 1));

2095 2096
    auto handle = backend->compile(func);
    handle->call_with_validate(
2097 2098
        {result_ht, result_ct},
        {src_layer_t, src_iter_t, weights_layer_t, weights_iter_t, biases_t});
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
    vector<float> expected_ht(10 * 100, 0.964028f);
    vector<float> expected_ct;
    for (size_t i = 0; i < 20 * 100; i++)
    {
        if (i < 1000)
        {
            expected_ct.push_back(0.964028f);
        }
        else
        {
            expected_ct.push_back(2.0f);
        }
    }

    EXPECT_TRUE(test::all_close(expected_ht, read_vector<float>(result_ht)));
    EXPECT_TRUE(test::all_close(expected_ct, read_vector<float>(result_ct)));
}
2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188
#else
TEST(cpu_fusion, rnn_fprop_1_lstm_cell)
{
    auto src_layer = make_shared<op::Parameter>(element::f32, Shape{10, 100});
    auto src_iter = make_shared<op::Parameter>(element::f32, Shape{10, 100});
    auto src_iter_c = make_shared<op::Parameter>(element::f32, Shape{10, 100});
    auto weights_layer = make_shared<op::Parameter>(element::f32, Shape{100, 400});
    auto weights_iter = make_shared<op::Parameter>(element::f32, Shape{100, 400});
    auto biases = make_shared<op::Parameter>(element::f32, Shape{400});
    const int number_of_timesteps = 1;
    const int number_of_gates_per_cell = 4;
    const int src_seq_length = 1;
    const int num_rnn_cell_states = 2;
    const int rnn_direction = 1;
    const int num_of_rnn_fused_layer = 1;
    ngraph::runtime::cpu::rnn_utils::rnntype rnn_type =
        ngraph::runtime::cpu::rnn_utils::rnntype::vanilla_lstm;

    auto rnn_node = make_shared<op::Rnn>(src_layer,
                                         src_iter,
                                         src_iter_c,
                                         weights_layer,
                                         weights_iter,
                                         biases,
                                         number_of_timesteps,
                                         number_of_gates_per_cell,
                                         src_seq_length,
                                         num_rnn_cell_states,
                                         rnn_direction,
                                         num_of_rnn_fused_layer,
                                         rnn_type);

    auto rnn_ht_output = make_shared<op::GetOutputElement>(rnn_node, 1);
    auto rnn_ct_output = make_shared<op::GetOutputElement>(rnn_node, 2);

    auto func = make_shared<Function>(
        NodeVector{rnn_ht_output, rnn_ct_output},
        ParameterVector{src_layer, src_iter, src_iter_c, weights_layer, weights_iter, biases});
    auto backend = runtime::Backend::create("CPU");

    shared_ptr<runtime::Tensor> src_layer_t =
        backend->create_tensor(element::f32, src_layer->get_shape());
    shared_ptr<runtime::Tensor> src_iter_t =
        backend->create_tensor(element::f32, src_iter->get_shape());
    shared_ptr<runtime::Tensor> src_iter_c_t =
        backend->create_tensor(element::f32, src_iter_c->get_shape());
    shared_ptr<runtime::Tensor> weights_layer_t =
        backend->create_tensor(element::f32, weights_layer->get_shape());
    shared_ptr<runtime::Tensor> weights_iter_t =
        backend->create_tensor(element::f32, weights_iter->get_shape());
    shared_ptr<runtime::Tensor> biases_t =
        backend->create_tensor(element::f32, biases->get_shape());
    shared_ptr<runtime::Tensor> result_ht = backend->create_tensor(element::f32, {10, 100});
    shared_ptr<runtime::Tensor> result_ct = backend->create_tensor(element::f32, Shape{10, 100});

    copy_data(src_layer_t, vector<float>(1000, 1));
    copy_data(src_iter_t, vector<float>(1000, 1));
    copy_data(src_iter_c_t, vector<float>(1000, 1));
    copy_data(weights_layer_t, vector<float>(400 * 100, 1));
    copy_data(weights_iter_t, vector<float>(400 * 100, 1));
    copy_data(biases_t, vector<float>(400, 1));

    auto handle = backend->compile(func);
    handle->call_with_validate(
        {result_ht, result_ct},
        {src_layer_t, src_iter_t, src_iter_c_t, weights_layer_t, weights_iter_t, biases_t});
    vector<float> expected_ht(10 * 100, 0.964028f);
    vector<float> expected_ct(10 * 100, 2.0f);

    EXPECT_TRUE(test::all_close(expected_ht, read_vector<float>(result_ht)));
    EXPECT_TRUE(test::all_close(expected_ct, read_vector<float>(result_ct)));
}
#endif
2189

2190
void sigmoid_multiply_fusion_forward_compute(runtime::Backend* backend,
2191
                                             const ParameterVector& input_params,
2192 2193 2194 2195 2196 2197 2198
                                             const vector<vector<float>>& input_data,
                                             const vector<Shape>& input_shapes,
                                             const Shape& result_shape,
                                             shared_ptr<Node> input_0_node,
                                             shared_ptr<Node> input_1_node,
                                             const vector<float>& expected)
{
2199
    shared_ptr<runtime::Tensor> result_tensor = backend->create_tensor(element::f32, result_shape);
2200

2201
    vector<shared_ptr<runtime::Tensor>> input_tensors;
2202
    for (size_t i = 0; i < input_params.size(); ++i)
2203 2204 2205 2206 2207 2208 2209
    {
        input_tensors.push_back(backend->create_tensor(element::f32, input_shapes[i]));
        copy_data(input_tensors[i], input_data[i]);
    }

    auto mul_node = input_0_node * input_1_node;
    auto func = make_shared<Function>(mul_node, input_params);
2210
    auto handle = backend->compile(func);
2211
    handle->call_with_validate({result_tensor}, input_tensors);
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231
    EXPECT_TRUE(test::all_close(read_vector<float>(result_tensor), expected));
}

TEST(cpu_fusion, sigmoid_multiply_fusion_forward)
{
    auto backend = runtime::Backend::create("CPU");

    Shape data_shape{1, 1, 2, 2};
    Shape const_shape{1};

    vector<float> input_0_data{1.f, 2.f, 3.f, 4.f};
    vector<float> input_1_data{1.2f, 2.3f, 3.5f, 4.7f};
    vector<float> const_data{1.2f};
    {
        auto input_0_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_1_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_2_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto sigmoid_0 = make_shared<op::Sigmoid>(input_0_param);
        auto sigmoid_1 = make_shared<op::Add>(input_1_param, input_2_param);
        vector<float> expected{1.60833f, 3.78743f, 6.19173f, 8.54352f};
2232
        ParameterVector input_params{input_0_param, input_1_param, input_2_param};
2233 2234
        vector<vector<float>> input_data{input_0_data, input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape, data_shape};
2235
        sigmoid_multiply_fusion_forward_compute(backend.get(),
2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
                                                input_params,
                                                input_data,
                                                input_shapes,
                                                data_shape,
                                                sigmoid_0,
                                                sigmoid_1,
                                                expected);
    }
    {
        auto input_0_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_1_param = make_shared<op::Parameter>(element::f32, const_shape);
        auto sigmoid_0 = make_shared<op::Broadcast>(input_1_param, data_shape, AxisSet{1, 2, 3});
        auto sigmoid_1 = make_shared<op::Sigmoid>(input_0_param);
        vector<float> expected{0.87727f, 1.05696f, 1.14309f, 1.17842f};
2250
        ParameterVector input_params{input_0_param, input_1_param};
2251 2252
        vector<vector<float>> input_data{input_0_data, const_data};
        vector<Shape> input_shapes{data_shape, const_shape};
2253
        sigmoid_multiply_fusion_forward_compute(backend.get(),
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267
                                                input_params,
                                                input_data,
                                                input_shapes,
                                                data_shape,
                                                sigmoid_0,
                                                sigmoid_1,
                                                expected);
    }
    {
        auto input_0_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_1_param = make_shared<op::Parameter>(element::f32, const_shape);
        auto sigmoid_0 = make_shared<op::Sigmoid>(input_0_param);
        auto sigmoid_1 = make_shared<op::Broadcast>(input_1_param, data_shape, AxisSet{1, 2, 3});
        vector<float> expected{0.87727f, 1.05696f, 1.14309f, 1.17842f};
2268
        ParameterVector input_params{input_0_param, input_1_param};
2269 2270
        vector<vector<float>> input_data{input_0_data, const_data};
        vector<Shape> input_shapes{data_shape, const_shape};
2271
        sigmoid_multiply_fusion_forward_compute(backend.get(),
2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
                                                input_params,
                                                input_data,
                                                input_shapes,
                                                data_shape,
                                                sigmoid_0,
                                                sigmoid_1,
                                                expected);
    }
    {
        auto input_0_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_1_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto sigmoid_0 = make_shared<op::Sigmoid>(input_0_param);
        auto sigmoid_1 = make_shared<op::Sigmoid>(input_1_param);
        vector<float> expected{0.561837f, 0.800536f, 0.924652f, 0.973163f};
2286
        ParameterVector input_params{input_0_param, input_1_param};
2287 2288
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2289
        sigmoid_multiply_fusion_forward_compute(backend.get(),
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
                                                input_params,
                                                input_data,
                                                input_shapes,
                                                data_shape,
                                                sigmoid_0,
                                                sigmoid_1,
                                                expected);
    }
    {
        auto input_0_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_1_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto sigmoid_0 = make_shared<op::Sigmoid>(input_0_param);
        auto sigmoid_1 = make_shared<op::Tanh>(input_1_param);
        vector<float> expected{0.60945f, 0.863266f, 0.950838f, 0.981851f};
2304
        ParameterVector input_params{input_0_param, input_1_param};
2305 2306
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2307
        sigmoid_multiply_fusion_forward_compute(backend.get(),
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321
                                                input_params,
                                                input_data,
                                                input_shapes,
                                                data_shape,
                                                sigmoid_0,
                                                sigmoid_1,
                                                expected);
    }
    {
        auto input_0_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_1_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto sigmoid_0 = make_shared<op::Tanh>(input_0_param);
        auto sigmoid_1 = make_shared<op::Sigmoid>(input_1_param);
        vector<float> expected{0.585304f, 0.876182f, 0.965887f, 0.990322f};
2322
        ParameterVector input_params{input_0_param, input_1_param};
2323 2324
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2325
        sigmoid_multiply_fusion_forward_compute(backend.get(),
2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339
                                                input_params,
                                                input_data,
                                                input_shapes,
                                                data_shape,
                                                sigmoid_0,
                                                sigmoid_1,
                                                expected);
    }
    {
        auto input_0_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_1_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto sigmoid_0 = make_shared<op::Tanh>(input_0_param);
        auto sigmoid_1 = make_shared<op::Tanh>(input_1_param);
        vector<float> expected{0.634907f, 0.94484f, 0.993242f, 0.999164f};
2340
        ParameterVector input_params{input_0_param, input_1_param};
2341 2342
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2343
        sigmoid_multiply_fusion_forward_compute(backend.get(),
2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
                                                input_params,
                                                input_data,
                                                input_shapes,
                                                data_shape,
                                                sigmoid_0,
                                                sigmoid_1,
                                                expected);
    }
}

2354
void sigmoid_multiply_fusion_backward_compute(runtime::Backend* backend,
2355
                                              const ParameterVector& input_params,
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368
                                              const vector<vector<float>>& input_data,
                                              const vector<Shape>& input_shapes,
                                              const vector<float> delta_data,
                                              const Shape& delta_shape,
                                              const Shape& d_input_0_shape,
                                              const Shape& d_input_1_shape,
                                              shared_ptr<Node> input_0_node,
                                              shared_ptr<Node> input_1_node,
                                              shared_ptr<Node> input_0_adjoint,
                                              shared_ptr<Node> input_1_adjoint,
                                              const vector<float>& expected_0,
                                              const vector<float>& expected_1)
{
2369
    vector<shared_ptr<runtime::Tensor>> input_tensors;
2370
    for (size_t i = 0; i < input_params.size(); ++i)
2371 2372 2373 2374 2375 2376
    {
        input_tensors.push_back(backend->create_tensor(element::f32, input_shapes[i]));
        copy_data(input_tensors[i], input_data[i]);
    }

    auto delta_param = make_shared<op::Parameter>(element::f32, delta_shape);
2377
    shared_ptr<runtime::Tensor> delta_tensor = backend->create_tensor(element::f32, delta_shape);
2378 2379
    copy_data(delta_tensor, delta_data);

2380
    ParameterVector back_params(input_params);
2381 2382 2383
    back_params.push_back(delta_param);
    input_tensors.push_back(delta_tensor);

2384
    shared_ptr<runtime::Tensor> d_input_0_tensor =
2385
        backend->create_tensor(element::f32, d_input_0_shape);
2386
    shared_ptr<runtime::Tensor> d_input_1_tensor =
2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400
        backend->create_tensor(element::f32, d_input_1_shape);

    using FunctionType = op::SigmoidMultiply::FunctionType;
    auto input_0_type = op::SigmoidMultiply::identify_node_type(input_0_node);
    auto input_1_type = op::SigmoidMultiply::identify_node_type(input_1_node);
    // for Identity functions, we use the node itself, otherwise use its input
    // where we will apply the function of input node
    auto input_0_alt =
        (input_0_type == FunctionType::Identity) ? input_0_node : input_0_node->get_argument(0);
    auto input_1_alt =
        (input_1_type == FunctionType::Identity) ? input_1_node : input_1_node->get_argument(0);
    auto sigmoid_mul =
        make_shared<op::SigmoidMultiply>(input_0_alt, input_1_alt, input_0_type, input_1_type);

2401
    ngraph::autodiff::Adjoints adjoints(OutputVector{sigmoid_mul}, OutputVector{delta_param});
2402 2403 2404
    auto d_input_0 = adjoints.backprop_node(input_0_adjoint);
    auto d_input_1 = adjoints.backprop_node(input_1_adjoint);
    auto df = make_shared<Function>(NodeVector{d_input_0, d_input_1}, back_params);
2405 2406
    auto handle = backend->compile(df);
    handle->call_with_validate({d_input_0_tensor, d_input_1_tensor}, input_tensors);
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
    EXPECT_TRUE(test::all_close(read_vector<float>(d_input_0_tensor), expected_0));
    EXPECT_TRUE(test::all_close(read_vector<float>(d_input_1_tensor), expected_1));
}

TEST(cpu_fusion, sigmoid_multiply_fusion_backward)
{
    auto backend = runtime::Backend::create("CPU");

    Shape data_shape{1, 1, 2, 2};
    Shape const_shape{1};

    vector<float> input_0_data{1.f, 2.f, 3.f, 4.f};
    vector<float> input_1_data{1.2f, 2.2f, 3.2f, 4.2f};
    vector<float> const_data{1.2f};
    vector<float> delta_data(shape_size(data_shape), 20.0f);

    {
        auto input_0_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_1_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_2_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto sigmoid_0 = make_shared<op::Sigmoid>(input_0_param);
        auto sigmoid_1 = make_shared<op::Add>(input_1_param, input_2_param);
        vector<float> expected_0{8.65093f, 8.81946f, 5.60191f, 2.89668f};
        vector<float> expected_1{14.6212f, 17.6159f, 19.0515f, 19.6403f};
2431
        ParameterVector input_params{input_0_param, input_1_param, input_2_param};
2432 2433
        vector<vector<float>> input_data{input_0_data, input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape, data_shape};
2434
        sigmoid_multiply_fusion_backward_compute(backend.get(),
2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
                                                 input_params,
                                                 input_data,
                                                 input_shapes,
                                                 delta_data,
                                                 data_shape,
                                                 data_shape,
                                                 data_shape,
                                                 sigmoid_0,
                                                 sigmoid_1,
                                                 input_0_param,
                                                 sigmoid_1,
                                                 expected_0,
                                                 expected_1);
    }
    {
        auto input_0_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_1_param = make_shared<op::Parameter>(element::f32, const_shape);
        auto sigmoid_0 = make_shared<op::Broadcast>(input_1_param, data_shape, AxisSet{1, 2, 3});
        auto sigmoid_1 = make_shared<op::Tanh>(input_0_param);
        vector<float> expected_0{15.2319f, 19.2806f, 19.9011f, 19.9866f};
        vector<float> expected_1{10.0794f, 1.69562f, 0.236785f, 0.0321828f};
2456
        ParameterVector input_params{input_0_param, input_1_param};
2457 2458
        vector<vector<float>> input_data{input_0_data, const_data};
        vector<Shape> input_shapes{data_shape, const_shape};
2459
        sigmoid_multiply_fusion_backward_compute(backend.get(),
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
                                                 input_params,
                                                 input_data,
                                                 input_shapes,
                                                 delta_data,
                                                 data_shape,
                                                 data_shape,
                                                 data_shape,
                                                 sigmoid_0,
                                                 sigmoid_1,
                                                 sigmoid_0,
                                                 input_0_param,
                                                 expected_0,
                                                 expected_1);
    }
    {
        auto input_0_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_1_param = make_shared<op::Parameter>(element::f32, const_shape);
        auto sigmoid_0 = make_shared<op::Tanh>(input_0_param);
        auto sigmoid_1 = make_shared<op::Broadcast>(input_1_param, data_shape, AxisSet{1, 2, 3});
        vector<float> expected_0{10.0794f, 1.69562f, 0.236785f, 0.0321828f};
        vector<float> expected_1{15.2319f, 19.2806f, 19.9011f, 19.9866f};
2481
        ParameterVector input_params{input_0_param, input_1_param};
2482 2483
        vector<vector<float>> input_data{input_0_data, const_data};
        vector<Shape> input_shapes{data_shape, const_shape};
2484
        sigmoid_multiply_fusion_backward_compute(backend.get(),
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505
                                                 input_params,
                                                 input_data,
                                                 input_shapes,
                                                 delta_data,
                                                 data_shape,
                                                 data_shape,
                                                 data_shape,
                                                 sigmoid_0,
                                                 sigmoid_1,
                                                 input_0_param,
                                                 sigmoid_1,
                                                 expected_0,
                                                 expected_1);
    }
    {
        auto input_0_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_1_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto sigmoid_0 = make_shared<op::Sigmoid>(input_0_param);
        auto sigmoid_1 = make_shared<op::Sigmoid>(input_1_param);
        vector<float> expected_0{3.02202f, 1.89041f, 0.868146f, 0.348035f};
        vector<float> expected_1{2.60102f, 1.58192f, 0.716941f, 0.285879f};
2506
        ParameterVector input_params{input_0_param, input_1_param};
2507 2508
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2509
        sigmoid_multiply_fusion_backward_compute(backend.get(),
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
                                                 input_params,
                                                 input_data,
                                                 input_shapes,
                                                 delta_data,
                                                 data_shape,
                                                 data_shape,
                                                 data_shape,
                                                 sigmoid_0,
                                                 sigmoid_1,
                                                 input_0_param,
                                                 input_1_param,
                                                 expected_0,
                                                 expected_1);
    }
    {
        auto input_0_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_1_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto sigmoid_0 = make_shared<op::Sigmoid>(input_0_param);
        auto sigmoid_1 = make_shared<op::Tanh>(input_1_param);
        vector<float> expected_0{3.27813f, 2.04894f, 0.900536f, 0.353095f};
        vector<float> expected_1{4.45975f, 0.84425f, 0.126201f, 0.0176579f};
2531
        ParameterVector input_params{input_0_param, input_1_param};
2532 2533
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2534
        sigmoid_multiply_fusion_backward_compute(backend.get(),
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555
                                                 input_params,
                                                 input_data,
                                                 input_shapes,
                                                 delta_data,
                                                 data_shape,
                                                 data_shape,
                                                 data_shape,
                                                 sigmoid_0,
                                                 sigmoid_1,
                                                 input_0_param,
                                                 input_1_param,
                                                 expected_0,
                                                 expected_1);
    }
    {
        auto input_0_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_1_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto sigmoid_0 = make_shared<op::Tanh>(input_0_param);
        auto sigmoid_1 = make_shared<op::Sigmoid>(input_1_param);
        vector<float> expected_0{6.45521f, 1.27207f, 0.189593f, 0.0264228f};
        vector<float> expected_1{2.70967f, 1.7314f, 0.748913f, 0.29092f};
2556
        ParameterVector input_params{input_0_param, input_1_param};
2557 2558
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2559
        sigmoid_multiply_fusion_backward_compute(backend.get(),
2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
                                                 input_params,
                                                 input_data,
                                                 input_shapes,
                                                 delta_data,
                                                 data_shape,
                                                 data_shape,
                                                 data_shape,
                                                 sigmoid_0,
                                                 sigmoid_1,
                                                 input_0_param,
                                                 input_1_param,
                                                 expected_0,
                                                 expected_1);
    }
    {
        auto input_0_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto input_1_param = make_shared<op::Parameter>(element::f32, data_shape);
        auto sigmoid_0 = make_shared<op::Tanh>(input_0_param);
        auto sigmoid_1 = make_shared<op::Tanh>(input_1_param);
        vector<float> expected_0{7.00227f, 1.37874f, 0.196666f, 0.026807f};
        vector<float> expected_1{4.64603f, 0.924027f, 0.131829f, 0.0179692f};
2581
        ParameterVector input_params{input_0_param, input_1_param};
2582 2583
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2584
        sigmoid_multiply_fusion_backward_compute(backend.get(),
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599
                                                 input_params,
                                                 input_data,
                                                 input_shapes,
                                                 delta_data,
                                                 data_shape,
                                                 data_shape,
                                                 data_shape,
                                                 sigmoid_0,
                                                 sigmoid_1,
                                                 input_0_param,
                                                 input_1_param,
                                                 expected_0,
                                                 expected_1);
    }
}
2600

2601
static void check_bounded_relu(Shape param_shape, float constant_val)
2602
{
2603 2604 2605 2606 2607 2608 2609 2610 2611
    auto make_function = [](Shape input_shape, float alpha_val) {
        auto relu_input = std::make_shared<op::Parameter>(element::f32, input_shape);
        auto relu = std::make_shared<op::Relu>(relu_input);
        auto alpha = op::Constant::create<float>(
            element::f32, input_shape, std::vector<float>(1.0f, alpha_val));
        auto min = std::make_shared<op::Minimum>(relu, alpha);
        auto f = make_shared<Function>(NodeVector{min}, ParameterVector{relu_input});
        return f;
    };
2612

2613 2614 2615
    auto cpu_f = make_function(param_shape, constant_val);
    auto int_f = make_function(param_shape, constant_val);
    test::Uniform<float> rng(-10.0f, 10.0f);
2616 2617 2618 2619 2620 2621 2622 2623 2624 2625
    vector<vector<float>> args;

    for (shared_ptr<op::Parameter> param : int_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
2626 2627 2628

    EXPECT_EQ(1, count_ops_of_type<op::BoundedRelu>(cpu_f));
    EXPECT_TRUE(test::all_close(cpu_results.at(0), int_results.at(0), 1.0e-4f, 1.0e-4f));
2629
}
2630

2631
TEST(cpu_fusion, MLIR_DISABLE_TEST(fuse_bounded_relu_inter_vs_cpu))
2632
{
2633 2634 2635 2636
    check_bounded_relu(Shape{4, 3, 2, 2}, 6.0f);
    check_bounded_relu(Shape{4, 3}, 4.0f);
    check_bounded_relu(Shape{4, 3, 2}, 2.0f);
}
2637

2638
TEST(cpu_fusion, MLIR_DISABLE_TEST(fuse_dropout))
gaurides's avatar
gaurides committed
2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709
{
    auto make_function = [](Shape input_shape,
                            const uint32_t seed_val,
                            double one_minus_prob,
                            bool fuse,
                            bool use_seed) {
        auto input = std::make_shared<op::Parameter>(element::f32, input_shape);
        auto value = op::Constant::create(element::f32, input_shape, {one_minus_prob});
        auto const1 = op::Constant::create(input->get_element_type(), Shape{}, {1});

        auto gen_mask = std::make_shared<op::GenerateMask>(const1,
                                                           input->get_shape(),
                                                           input->get_element_type(),
                                                           seed_val,
                                                           one_minus_prob,
                                                           use_seed);

        auto mult = std::make_shared<op::Multiply>(gen_mask, input);

        auto goe = std::make_shared<op::GetOutputElement>(mult, 0);

        auto pdivide = fuse ? std::make_shared<op::Divide>(mult, value)
                            : std::make_shared<op::Divide>(goe, value);

        auto f = make_shared<Function>(NodeVector{pdivide, gen_mask}, ParameterVector{input});

        return f;
    };

    uint32_t seed = rand();
    auto fuse_func = make_function(Shape{2, 2, 256, 256}, seed, 0.9, true, true);
    auto fuse_func2 = make_function(Shape{2, 2, 256, 256}, seed, 0.9, true, true);
    auto nofuse_func = make_function(Shape{2, 2, 256, 256}, 1, 0.9, false, false);
    {
        pass::Manager pass_manager;
        pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
        pass_manager.run_passes(fuse_func);
        pass_manager.run_passes(nofuse_func);
        ASSERT_EQ(count_ops_of_type<op::Dropout>(fuse_func), 1);
        ASSERT_EQ(count_ops_of_type<op::GenerateMask>(fuse_func), 0);
        ASSERT_EQ(count_ops_of_type<op::Dropout>(nofuse_func), 0);
    }

    auto fuse_func3 = make_function(Shape{2, 2, 256, 256}, seed, 0.9, true, false);
    auto fuse_func4 = make_function(Shape{2, 2, 256, 256}, seed, 0.9, true, false);
    {
        test::Uniform<float> rng(1.0f, 100.0f);
        vector<vector<float>> args;
        for (shared_ptr<op::Parameter> param : fuse_func->get_parameters())
        {
            auto name = param->get_name();
            vector<float> tensor_val(shape_size(param->get_shape()));
            rng.initialize(tensor_val);
            args.push_back(tensor_val);
        }

        auto fuse_results = execute(fuse_func, args, "CPU");
        auto fuse_results2 = execute(fuse_func2, args, "CPU");
        EXPECT_TRUE(test::all_close(fuse_results.at(0), fuse_results2.at(0)));
        EXPECT_TRUE(test::all_close(fuse_results.at(1), fuse_results2.at(1)));

        auto fuse_results3 = execute(fuse_func3, args, "CPU");
        auto fuse_results4 = execute(fuse_func4, args, "CPU");
        EXPECT_FALSE(test::all_close(fuse_results3.at(0), fuse_results4.at(0)));
        EXPECT_FALSE(test::all_close(fuse_results3.at(1), fuse_results4.at(1)));

        // Note: Since the RNG used in Dropout kernel is different than RNG used in GenerateMask
        // kernel, we can't compare fuse_results and nofuse_results
    }
}

2710
TEST(cpu_fusion, MLIR_DISABLE_TEST(fuse_leaky_relu))
2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727
{
    auto make_function = [](Shape input_shape, vector<float> alpha_val) {
        auto input = std::make_shared<op::Parameter>(element::f32, input_shape);
        auto alpha = op::Constant::create<float>(element::f32, input_shape, alpha_val);
        auto out =
            std::make_shared<op::Maximum>(input, std::make_shared<op::Multiply>(input, alpha));
        auto f = make_shared<Function>(NodeVector{out}, ParameterVector{input});
        return f;
    };

    auto no_fuse1 = make_function(Shape{1, 2, 3}, std::vector<float>(6, -1.0f));
    auto no_fuse2 = make_function(Shape{1, 3}, std::vector<float>{1.4f, 1.2f, 1.4f});

    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
    pass_manager.run_passes(no_fuse1);
    pass_manager.run_passes(no_fuse2);
2728 2729
    EXPECT_EQ(0, count_ops_of_type<op::CPULeakyRelu>(no_fuse1));
    EXPECT_EQ(0, count_ops_of_type<op::CPULeakyRelu>(no_fuse2));
2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740

    // non-mkldnn kernel
    auto cpu_f1 = make_function(Shape{1, 2, 3}, std::vector<float>(6, 0.1f));
    // mkldnn kernel
    auto cpu_f2 = make_function(Shape{2, 3}, std::vector<float>(6, 0.1f));

    vector<vector<float>> args;
    args.push_back(std::vector<float>{-1, -2, 0, 1, 2, 3});
    std::vector<float> expected_result{-0.1f, -0.2f, 0.0f, 1.0f, 2.0f, 3.0f};

    auto cpu1_results = execute(cpu_f1, args, "CPU");
2741
    EXPECT_EQ(1, count_ops_of_type<op::CPULeakyRelu>(cpu_f1));
2742 2743 2744
    EXPECT_TRUE(test::all_close(cpu1_results.at(0), expected_result));

    auto cpu2_results = execute(cpu_f2, args, "CPU");
2745
    EXPECT_EQ(1, count_ops_of_type<op::CPULeakyRelu>(cpu_f2));
2746 2747 2748
    EXPECT_TRUE(test::all_close(cpu2_results.at(0), expected_result));
}

2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943
TEST(cpu_fusion, fuse_update_slice)
{
    auto make_function = [](bool fuse = true) {
        auto input = std::make_shared<op::Parameter>(element::f32, Shape{4, 32, 16});
        Shape lower_bounds{1, 0, 0};
        Shape upper_bounds{2, 32, 16};
        auto slice = std::make_shared<op::Slice>(
            input, fuse ? lower_bounds : Shape{3, 0, 0}, fuse ? upper_bounds : Shape{4, 32, 16});
        auto update = std::make_shared<op::Parameter>(element::f32, Shape{1, 32, 16});
        auto add = std::make_shared<op::Add>(slice, update);
        auto out = std::make_shared<op::ReplaceSlice>(input, add, lower_bounds, upper_bounds);
        auto f = make_shared<Function>(NodeVector{out}, ParameterVector{input, update});
        return f;
    };

    auto fuse = make_function(true);
    auto no_fuse = make_function(false);

    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
    pass_manager.run_passes(fuse);
    pass_manager.run_passes(no_fuse);
    EXPECT_EQ(1, count_ops_of_type<op::UpdateSlice>(fuse));
    EXPECT_EQ(0, count_ops_of_type<op::UpdateSlice>(no_fuse));

    auto int_f = make_function();
    auto cpu_f = make_function();

    test::Uniform<float> rng(0.0f, 1.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : int_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i)));
    }
}

TEST(cpu_fusion, fuse_update_slice_inplace)
{
    auto make_function = [](bool fuse = true) {
        auto input = std::make_shared<op::Parameter>(element::f32, Shape{4, 32, 16});
        auto abs = std::make_shared<op::Abs>(input);
        Shape lower_bounds{1, 0, 0};
        Shape upper_bounds{2, 32, 16};
        auto slice = std::make_shared<op::Slice>(abs, lower_bounds, upper_bounds);
        auto update = std::make_shared<op::Parameter>(element::f32, Shape{1, 32, 16});
        auto add = std::make_shared<op::Add>(slice, update);
        auto rs = std::make_shared<op::ReplaceSlice>(abs, add, lower_bounds, upper_bounds);
        auto out = std::make_shared<op::Abs>(rs);
        if (fuse)
        {
            return make_shared<Function>(NodeVector{out}, ParameterVector{input, update});
        }
        else
        {
            return make_shared<Function>(NodeVector{out, add}, ParameterVector{input, update});
        }
    };

    auto fuse = make_function(true);
    auto no_fuse = make_function(false);

    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
    pass_manager.run_passes(fuse);
    pass_manager.run_passes(no_fuse);
    EXPECT_EQ(1, count_ops_of_type<op::UpdateSlice>(fuse));
    EXPECT_EQ(0, count_ops_of_type<op::UpdateSlice>(no_fuse));

    auto int_f = make_function();
    auto cpu_f = make_function();

    test::Uniform<float> rng(0.0f, 1.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : int_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i)));
    }
}

TEST(cpu_fusion, fuse_update_slice_strided)
{
    auto make_function = [](bool fuse = true) {
        auto input = std::make_shared<op::Parameter>(element::f32, Shape{4, 32, 16});
        Shape lower_bounds{1, 0, 0};
        Shape upper_bounds{2, 32, 16};
        Strides strides{1, 2, 2};
        auto slice = std::make_shared<op::Slice>(input,
                                                 fuse ? lower_bounds : Shape{3, 0, 0},
                                                 fuse ? upper_bounds : Shape{4, 32, 16},
                                                 strides);
        auto update = std::make_shared<op::Parameter>(element::f32, Shape{1, 16, 8});
        auto add = std::make_shared<op::Add>(slice, update);
        auto out =
            std::make_shared<op::ReplaceSlice>(input, add, lower_bounds, upper_bounds, strides);
        auto f = make_shared<Function>(NodeVector{out}, ParameterVector{input, update});
        return f;
    };

    auto fuse = make_function(true);
    auto no_fuse = make_function(false);

    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
    pass_manager.run_passes(fuse);
    pass_manager.run_passes(no_fuse);
    EXPECT_EQ(1, count_ops_of_type<op::UpdateSlice>(fuse));
    EXPECT_EQ(0, count_ops_of_type<op::UpdateSlice>(no_fuse));

    auto int_f = make_function();
    auto cpu_f = make_function();

    test::Uniform<float> rng(0.0f, 1.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : int_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i)));
    }
}

TEST(cpu_fusion, fuse_update_slice_strided_inplace)
{
    auto make_function = [](bool fuse = true) {
        auto input = std::make_shared<op::Parameter>(element::f32, Shape{4, 32, 16});
        auto abs = std::make_shared<op::Abs>(input);
        Shape lower_bounds{1, 0, 0};
        Shape upper_bounds{2, 32, 16};
        Strides strides{1, 4, 2};
        auto slice = std::make_shared<op::Slice>(abs, lower_bounds, upper_bounds, strides);
        auto update = std::make_shared<op::Parameter>(element::f32, Shape{1, 8, 8});
        auto add = std::make_shared<op::Add>(slice, update);
        auto rs = std::make_shared<op::ReplaceSlice>(abs, add, lower_bounds, upper_bounds, strides);
        auto out = std::make_shared<op::Abs>(rs);
        if (fuse)
        {
            return make_shared<Function>(NodeVector{out}, ParameterVector{input, update});
        }
        else
        {
            return make_shared<Function>(NodeVector{out, add}, ParameterVector{input, update});
        }
    };

    auto fuse = make_function(true);
    auto no_fuse = make_function(false);

    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
    pass_manager.run_passes(fuse);
    pass_manager.run_passes(no_fuse);
    EXPECT_EQ(1, count_ops_of_type<op::UpdateSlice>(fuse));
    EXPECT_EQ(0, count_ops_of_type<op::UpdateSlice>(no_fuse));

    auto int_f = make_function();
    auto cpu_f = make_function();

    test::Uniform<float> rng(0.0f, 1.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : int_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i)));
    }
}

2944 2945 2946 2947 2948 2949 2950 2951 2952
TEST(cpu_fusion, dot_batch_forward)
{
    const Shape shape_a{2, 3, 2};
    const Shape shape_b{2, 3};

    auto generate_func = [&shape_a, &shape_b]() -> shared_ptr<Function> {
        auto a = make_shared<op::Parameter>(element::f32, shape_a);
        auto b = make_shared<op::Parameter>(element::f32, shape_b);
        auto dot = make_shared<op::Dot>(a, b);
2953
        return make_shared<Function>(dot, ParameterVector{a, b});
2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973
    };
    shared_ptr<Function> cpu_func = generate_func();
    shared_ptr<Function> int_func = generate_func();

    test::Uniform<float> rng(0.0f, 1.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : int_func->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    auto int_results = execute(int_func, args, "INTERPRETER");
    auto cpu_results = execute(cpu_func, args, "CPU");
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f));
    }
}
2974

Pruthvi's avatar
Pruthvi committed
2975
static std::shared_ptr<Function>
2976
    create_rnn_input_linear_transformation_function(size_t num_timesteps, bool data_is_4d = false)
Pruthvi's avatar
Pruthvi committed
2977 2978 2979
{
    auto W = std::make_shared<op::Parameter>(element::f32, Shape{400, 50});
    auto bias = std::make_shared<op::Parameter>(element::f32, Shape{400});
2980
    ParameterVector params{W, bias};
Pruthvi's avatar
Pruthvi committed
2981
    auto create_graph = [&]() -> std::shared_ptr<Node> {
2982 2983 2984
        auto data_param = (data_is_4d)
                              ? std::make_shared<op::Parameter>(element::f32, Shape{2, 5, 1, 50})
                              : std::make_shared<op::Parameter>(element::f32, Shape{10, 1, 50});
Pruthvi's avatar
Pruthvi committed
2985
        params.push_back(data_param);
2986
        auto reshape_axis_order = data_is_4d ? AxisVector{0, 1, 2, 3} : AxisVector{0, 1, 2};
Pruthvi's avatar
Pruthvi committed
2987
        auto data_param_reshape =
2988
            std::make_shared<op::Reshape>(data_param, reshape_axis_order, Shape{10, 50});
Pruthvi's avatar
Pruthvi committed
2989 2990 2991 2992
        auto W_reshape = std::make_shared<op::Reshape>(W, AxisVector{1, 0}, Shape{50, 400});
        auto dot = std::make_shared<op::Dot>(data_param_reshape, W_reshape);
        auto bias_broadcast = make_shared<op::Broadcast>(bias, dot->get_shape(), AxisSet{0});
        auto add_bias = std::make_shared<op::Add>(dot, bias_broadcast);
2993
        return move(add_bias);
Pruthvi's avatar
Pruthvi committed
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016
    };

    NodeVector graph_nodes;
    for (size_t i = 0; i < num_timesteps; i++)
    {
        graph_nodes.push_back(create_graph());
    }
    auto concat = std::make_shared<op::Concat>(graph_nodes, 0);
    return make_shared<Function>(NodeVector{concat}, params);
}

TEST(cpu_fusion, fuse_rnn_input_across_time_steps)
{
    auto func = create_rnn_input_linear_transformation_function(10);
    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPURnnMatFusion>();
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
    pass_manager.run_passes(func);
    size_t ref_matmulbias_count = 1;
    auto matmulbias_count = count_ops_of_type<op::MatmulBias>(func);
    EXPECT_EQ(ref_matmulbias_count, matmulbias_count);
}

3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
TEST(cpu_fusion, fuse_rnn_input_across_time_steps_4d_data)
{
    auto func = create_rnn_input_linear_transformation_function(10, true);
    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPURnnMatFusion>();
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
    pass_manager.run_passes(func);
    size_t ref_matmulbias_count = 10; // no CPURnnMatFusion transformations
    auto matmulbias_count = count_ops_of_type<op::MatmulBias>(func);
    EXPECT_EQ(ref_matmulbias_count, matmulbias_count);
}

Pruthvi's avatar
Pruthvi committed
3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
TEST(cpu_fusion, rnn_input_fusion_inter_vs_cpu)
{
    shared_ptr<Function> cpu_func = create_rnn_input_linear_transformation_function(10);
    shared_ptr<Function> int_func = create_rnn_input_linear_transformation_function(10);

    test::Uniform<float> rng(-10.0f, 10.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : int_func->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    auto int_results = execute(int_func, args, "INTERPRETER");
    auto cpu_results = execute(cpu_func, args, "CPU");
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f));
    }
}
3050

3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075
TEST(cpu_quant_fusion, qconv_relu)
{
    auto make_function = []() {
        Shape shape_input{1, 2, 2, 2};
        Shape shape_weights{1, 2, 1, 1};
        auto input = std::make_shared<op::Parameter>(element::f32, shape_input);
        auto weights = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto input_scale = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto weights_scale = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto output_scale = op::Constant::create(element::f32, Shape{}, {4.0f});
        auto int8_zero = op::Constant::create(element::i8, Shape{}, {0});
        auto uint8_zero = op::Constant::create(element::u8, Shape{}, {0});

        op::Quantize::RoundMode round_mode = op::Quantize::RoundMode::ROUND_NEAREST_TOWARD_EVEN;
        auto q_input = std::make_shared<op::Quantize>(
            input, input_scale, uint8_zero, element::u8, AxisSet{}, round_mode);
        auto q_weights = std::make_shared<op::Quantize>(
            weights, weights_scale, int8_zero, element::i8, AxisSet{}, round_mode);
        auto conv = std::make_shared<op::QuantizedConvolution>(q_input,
                                                               q_weights,
                                                               Strides{1, 1},
                                                               Strides{1, 1},
                                                               CoordinateDiff{0, 0},
                                                               CoordinateDiff{0, 0},
                                                               Strides{1, 1},
3076 3077 3078 3079 3080 3081 3082
                                                               input_scale,
                                                               uint8_zero,
                                                               weights_scale,
                                                               int8_zero,
                                                               output_scale,
                                                               int8_zero,
                                                               element::i8,
3083 3084
                                                               AxisSet{},
                                                               AxisSet{},
3085
                                                               AxisSet{});
3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
        auto dq = std::make_shared<op::Dequantize>(
            conv, output_scale, int8_zero, element::f32, AxisSet{});
        auto relu = std::make_shared<op::Relu>(dq);
        auto q = std::make_shared<op::Quantize>(
            relu, output_scale, uint8_zero, element::u8, AxisSet{}, round_mode);
        auto q_f =
            std::make_shared<op::Dequantize>(q, output_scale, uint8_zero, element::f32, AxisSet{});
        return make_shared<Function>(NodeVector{q_f}, ParameterVector{input, weights});
    };

    auto cpu_f1 = make_function();
    auto cpu_f2 = make_function();

    test::Uniform<float> rng(2.0f, 2.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : cpu_f1->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:0", 1);
    auto cpu1_results = execute(cpu_f1, args, "CPU");
    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:1", 1);
    auto cpu2_results = execute(cpu_f2, args, "CPU");
    // Expected output - [2, 2, ...]
    EXPECT_TRUE(test::all_close(cpu1_results.at(0), cpu2_results.at(0)));
}
3115

3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175
TEST(cpu_quant_fusion, qconvb_relu)
{
    auto make_function = []() {
        Shape shape_input{1, 2, 2, 2};
        Shape shape_weights{1, 2, 1, 1};
        auto input = std::make_shared<op::Parameter>(element::f32, shape_input);
        auto weights = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto bias = std::make_shared<op::Parameter>(element::f32, Shape{shape_weights[0]});
        auto input_scale = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto weights_scale = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto output_scale = op::Constant::create(element::f32, Shape{}, {4.0f});
        auto int8_zero = op::Constant::create(element::i8, Shape{}, {0});
        auto int32_zero = op::Constant::create(element::i32, Shape{}, {0});
        auto uint8_zero = op::Constant::create(element::u8, Shape{}, {0});

        op::Quantize::RoundMode round_mode = op::Quantize::RoundMode::ROUND_NEAREST_TOWARD_EVEN;
        auto q_input = std::make_shared<op::Quantize>(
            input, input_scale, uint8_zero, element::u8, AxisSet{}, round_mode);
        auto q_weights = std::make_shared<op::Quantize>(
            weights, weights_scale, int8_zero, element::i8, AxisSet{}, round_mode);
        auto q_bias = std::make_shared<op::Quantize>(
            bias, input_scale * weights_scale, int32_zero, element::i32, AxisSet{}, round_mode);
        auto requant_scale = (input_scale * weights_scale) / output_scale;
        auto conv = std::make_shared<op::QuantizedConvolutionBias>(q_input,
                                                                   q_weights,
                                                                   bias,
                                                                   Strides{1, 1},
                                                                   Strides{1, 1},
                                                                   CoordinateDiff{0, 0},
                                                                   CoordinateDiff{0, 0},
                                                                   Strides{1, 1},
                                                                   requant_scale);
        auto dq = std::make_shared<op::Dequantize>(
            conv, output_scale, int8_zero, element::f32, AxisSet{});
        auto relu = std::make_shared<op::Relu>(dq);
        auto q = std::make_shared<op::Quantize>(
            relu, output_scale, uint8_zero, element::u8, AxisSet{}, round_mode);
        auto q_f =
            std::make_shared<op::Dequantize>(q, output_scale, uint8_zero, element::f32, AxisSet{});
        return make_shared<Function>(NodeVector{q_f}, ParameterVector{input, weights, bias});
    };

    auto cpu_f1 = make_function();
    auto cpu_f2 = make_function();

    test::Uniform<float> rng(2.0f, 2.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : cpu_f1->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:0", 1);
    auto cpu1_results = execute(cpu_f1, args, "CPU");
    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:1", 1);
    auto cpu2_results = execute(cpu_f2, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu1_results.at(0), cpu2_results.at(0)));
}

3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251
TEST(cpu_quant_fusion, qavg_pool)
{
    auto make_function = []() {
        Shape shape_input{1, 2, 4, 4};
        auto input = std::make_shared<op::Parameter>(element::f32, shape_input);
        auto input_scale = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto weights_scale = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto int8_zero = op::Constant::create(element::i8, Shape{}, {0});
        auto uint8_zero = op::Constant::create(element::u8, Shape{}, {0});

        op::Quantize::RoundMode round_mode = op::Quantize::RoundMode::ROUND_NEAREST_TOWARD_EVEN;
        auto q_input = std::make_shared<op::Quantize>(
            input, input_scale, uint8_zero, element::u8, AxisSet{}, round_mode);
        auto dq = std::make_shared<op::Dequantize>(
            q_input, input_scale, uint8_zero, element::f32, AxisSet{});
        auto avg_pool = std::make_shared<op::AvgPool>(dq, Shape{2, 2});
        return make_shared<Function>(NodeVector{avg_pool}, ParameterVector{input});
    };

    auto cpu_f1 = make_function();
    auto cpu_f2 = make_function();

    test::Uniform<float> rng(4.0f, 4.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : cpu_f1->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:0", 1);
    auto cpu1_results = execute(cpu_f1, args, "CPU");
    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:1", 1);
    auto cpu2_results = execute(cpu_f2, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu1_results.at(0), cpu2_results.at(0)));
}

TEST(cpu_quant_fusion, qmax_pool)
{
    auto make_function = []() {
        Shape shape_input{1, 2, 4, 4};
        auto input = std::make_shared<op::Parameter>(element::f32, shape_input);
        auto input_scale = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto weights_scale = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto int8_zero = op::Constant::create(element::i8, Shape{}, {0});
        auto uint8_zero = op::Constant::create(element::u8, Shape{}, {0});

        op::Quantize::RoundMode round_mode = op::Quantize::RoundMode::ROUND_NEAREST_TOWARD_EVEN;
        auto q_input = std::make_shared<op::Quantize>(
            input, input_scale, uint8_zero, element::u8, AxisSet{}, round_mode);
        auto dq = std::make_shared<op::Dequantize>(
            q_input, input_scale, uint8_zero, element::f32, AxisSet{});
        auto maxpool = std::make_shared<op::MaxPool>(dq, Shape{2, 2});
        return make_shared<Function>(NodeVector{maxpool}, ParameterVector{input});
    };

    auto cpu_f1 = make_function();
    auto cpu_f2 = make_function();

    test::Uniform<float> rng(1.0f, 10.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : cpu_f1->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:0", 1);
    auto cpu1_results = execute(cpu_f1, args, "CPU");
    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:1", 1);
    auto cpu2_results = execute(cpu_f2, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu1_results.at(0), cpu2_results.at(0)));
}

3252
TEST(cpu_quant_fusion, MLIR_DISABLE_TEST(qconcat))
3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299
{
    auto make_function = []() {
        auto get_input_slice = [](std::shared_ptr<op::Parameter>& input) {
            auto input_scale = op::Constant::create(element::f32, Shape{}, {2.0f});
            auto int8_zero = op::Constant::create(element::i8, Shape{}, {0});
            auto uint8_zero = op::Constant::create(element::u8, Shape{}, {0});

            op::Quantize::RoundMode round_mode = op::Quantize::RoundMode::ROUND_NEAREST_TOWARD_EVEN;
            auto q_input = std::make_shared<op::Quantize>(
                input, input_scale, uint8_zero, element::u8, AxisSet{}, round_mode);
            auto dq = std::make_shared<op::Dequantize>(
                q_input, input_scale, uint8_zero, element::f32, AxisSet{});
            return dq;
        };

        NodeVector concat_inputs, concats;
        ParameterVector inputs;
        Shape shape_input{1, 2, 4, 4};
        inputs.push_back(std::make_shared<op::Parameter>(element::f32, shape_input));
        concat_inputs.push_back(get_input_slice(inputs.back()));
        // Concat2  -- Concat7
        for (size_t i = 0; i < 6; i++)
        {
            inputs.push_back(std::make_shared<op::Parameter>(element::f32, shape_input));
            concat_inputs.push_back(get_input_slice(inputs.back()));
            concats.push_back(std::make_shared<op::Concat>(concat_inputs, 0));
        }
        return make_shared<Function>(concats, inputs);
    };

    auto cpu_f1 = make_function();
    auto cpu_f2 = make_function();

    test::Uniform<float> rng(2.0f, 2.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : cpu_f1->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:0", 1);
    auto cpu1_results = execute(cpu_f1, args, "CPU");
    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:1", 1);
    auto cpu2_results = execute(cpu_f2, args, "CPU");
    // Expect Concat2 -- Concat6 to be fused and not Concat7
3300
    ASSERT_EQ(count_ops_of_type<op::Concat>(cpu_f2), 6);
3301 3302 3303
    EXPECT_TRUE(test::all_close(cpu1_results.at(0), cpu2_results.at(0)));
}

3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513
TEST(cpu_quant_fusion, dq_q)
{
    auto make_function = [](bool match_scales = true, bool match_et = true) {
        Shape shape_input{1, 2, 2};
        auto input = std::make_shared<op::Parameter>(element::i8, shape_input);
        auto dq_scale = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto int8_zero = op::Constant::create(element::i8, Shape{}, {0});
        auto dq =
            std::make_shared<op::Dequantize>(input, dq_scale, int8_zero, element::f32, AxisSet{});
        float q_scalev = 2.0f;
        if (!match_scales)
        {
            q_scalev = 1.0f;
        }
        auto q_scale = op::Constant::create(element::f32, Shape{}, {q_scalev});
        op::Quantize::RoundMode round_mode = op::Quantize::RoundMode::ROUND_NEAREST_TOWARD_EVEN;
        if (match_et)
        {
            auto q = std::make_shared<op::Quantize>(
                dq, q_scale, int8_zero, element::i8, AxisSet{}, round_mode);
            return make_shared<Function>(NodeVector{q}, ParameterVector{input});
        }
        else
        {
            auto uint8_zero = op::Constant::create(element::u8, Shape{}, {0});
            auto q = std::make_shared<op::Quantize>(
                dq, q_scale, uint8_zero, element::u8, AxisSet{}, round_mode);
            return make_shared<Function>(NodeVector{q}, ParameterVector{input});
        }
    };

    auto cpu_f1 = make_function();
    auto cpu_f2 = make_function();

    vector<vector<int8_t>> args;
    args.push_back({-1, 2, 3, 4});

    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:0", 1);
    auto cpu1_results = execute(cpu_f1, args, "CPU");
    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:1", 1);
    auto cpu2_results = execute(cpu_f2, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu1_results.at(0), cpu2_results.at(0)));

    auto backend = runtime::Backend::create("CPU");
    auto fuse = make_function(true, true);
    auto no_fuse1 = make_function(false, true);
    auto no_fuse2 = make_function(true, false);
    backend->compile(fuse);
    backend->compile(no_fuse1);
    backend->compile(no_fuse2);
    ASSERT_EQ(count_ops_of_type<op::Quantize>(fuse), 0);
    ASSERT_EQ(count_ops_of_type<op::Quantize>(no_fuse1), 1);
    ASSERT_EQ(count_ops_of_type<op::Quantize>(no_fuse2), 1);
}

TEST(cpu_quant_fusion, qconvbsa)
{
    auto make_function = []() {
        Shape shape_input{1, 2, 2, 2};
        Shape shape_weights{1, 2, 1, 1};
        Shape shape_summand{1, 1, 2, 2};
        auto input = std::make_shared<op::Parameter>(element::f32, shape_input);
        auto weights = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto bias = std::make_shared<op::Parameter>(element::f32, Shape{shape_weights[0]});
        auto summand = std::make_shared<op::Parameter>(element::f32, shape_summand);

        auto input_scale = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto weights_scale = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto output_scale = op::Constant::create(element::f32, Shape{}, {4.0f});
        auto summand_scale = op::Constant::create(element::f32, Shape{}, {2.0f});

        auto int8_zero = op::Constant::create(element::i8, Shape{}, {0});
        auto int32_zero = op::Constant::create(element::i32, Shape{}, {0});
        auto uint8_zero = op::Constant::create(element::u8, Shape{}, {0});

        op::Quantize::RoundMode round_mode = op::Quantize::RoundMode::ROUND_NEAREST_TOWARD_EVEN;
        auto q_input = std::make_shared<op::Quantize>(
            input, input_scale, uint8_zero, element::u8, AxisSet{}, round_mode);
        auto q_weights = std::make_shared<op::Quantize>(
            weights, weights_scale, int8_zero, element::i8, AxisSet{}, round_mode);
        auto q_bias = std::make_shared<op::Quantize>(
            bias, input_scale * weights_scale, int32_zero, element::i32, AxisSet{}, round_mode);
        auto q_summand = std::make_shared<op::Quantize>(
            summand, summand_scale, int8_zero, element::i8, AxisSet{}, round_mode);

        // Left Graph
        auto requant_scale = (input_scale * weights_scale) / output_scale;
        auto conv = std::make_shared<op::QuantizedConvolutionBias>(q_input,
                                                                   q_weights,
                                                                   bias,
                                                                   Strides{1, 1},
                                                                   Strides{1, 1},
                                                                   CoordinateDiff{0, 0},
                                                                   CoordinateDiff{0, 0},
                                                                   Strides{1, 1},
                                                                   requant_scale);
        auto dq_l = std::make_shared<op::Dequantize>(
            conv, output_scale, int8_zero, element::f32, AxisSet{});
        auto r_l = std::make_shared<op::Reshape>(dq_l, AxisVector{0, 1, 2, 3}, Shape{1, 2, 2});
        auto b_l = std::make_shared<op::Broadcast>(r_l, Shape{1, 1, 2, 2}, AxisSet{0});

        // Right Graph
        auto dq_r = std::make_shared<op::Dequantize>(
            q_summand, summand_scale, int8_zero, element::f32, AxisSet{});
        auto r_r = std::make_shared<op::Reshape>(dq_r, AxisVector{0, 1, 2, 3}, Shape{1, 2, 2});
        auto b_r = std::make_shared<op::Broadcast>(r_r, Shape{1, 1, 2, 2}, AxisSet{0});
        auto add = b_l + b_r;
        auto relu = std::make_shared<op::Relu>(add);
        return make_shared<Function>(NodeVector{relu},
                                     ParameterVector{input, weights, bias, summand});
    };

    auto cpu_f1 = make_function();
    auto cpu_f2 = make_function();

    test::Uniform<float> rng(4.0f, 4.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : cpu_f1->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    // Disable CPUQuantFusion
    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:0", 1);
    auto cpu1_results = execute(cpu_f1, args, "CPU");
    // Enable CPUQuantFusion
    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:1", 1);
    auto cpu2_results = execute(cpu_f2, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu1_results.at(0), cpu2_results.at(0)));
}

TEST(cpu_quant_fusion, qconvba)
{
    auto make_function = []() {
        Shape shape_input{1, 2, 2, 2};
        Shape shape_weights{1, 2, 1, 1};
        Shape shape_summand{1, 1, 2, 2};
        auto input = std::make_shared<op::Parameter>(element::f32, shape_input);
        auto weights = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto bias = std::make_shared<op::Parameter>(element::f32, Shape{shape_weights[0]});
        auto summand = std::make_shared<op::Parameter>(element::f32, shape_summand);

        auto input_scale = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto weights_scale = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto output_scale = op::Constant::create(element::f32, Shape{}, {4.0f});
        auto summand_scale = op::Constant::create(element::f32, Shape{}, {4.0f});

        auto int8_zero = op::Constant::create(element::i8, Shape{}, {0});
        auto int32_zero = op::Constant::create(element::i32, Shape{}, {0});
        auto uint8_zero = op::Constant::create(element::u8, Shape{}, {0});

        op::Quantize::RoundMode round_mode = op::Quantize::RoundMode::ROUND_NEAREST_TOWARD_EVEN;
        auto q_input = std::make_shared<op::Quantize>(
            input, input_scale, uint8_zero, element::u8, AxisSet{}, round_mode);
        auto q_weights = std::make_shared<op::Quantize>(
            weights, weights_scale, int8_zero, element::i8, AxisSet{}, round_mode);
        auto q_bias = std::make_shared<op::Quantize>(
            bias, input_scale * weights_scale, int32_zero, element::i32, AxisSet{}, round_mode);
        auto q_summand = std::make_shared<op::Quantize>(
            summand, summand_scale, uint8_zero, element::u8, AxisSet{}, round_mode);

        // Left Graph
        auto requant_scale = (input_scale * weights_scale) / output_scale;
        auto conv = std::make_shared<op::QuantizedConvolutionBias>(q_input,
                                                                   q_weights,
                                                                   bias,
                                                                   Strides{1, 1},
                                                                   Strides{1, 1},
                                                                   CoordinateDiff{0, 0},
                                                                   CoordinateDiff{0, 0},
                                                                   Strides{1, 1},
                                                                   requant_scale);
        auto dq_l = std::make_shared<op::Dequantize>(
            conv, output_scale, int8_zero, element::f32, AxisSet{});
        auto r_l = std::make_shared<op::Reshape>(dq_l, AxisVector{0, 1, 2, 3}, Shape{1, 2, 2});
        auto b_l = std::make_shared<op::Broadcast>(r_l, Shape{1, 1, 2, 2}, AxisSet{0});

        // Right Graph
        auto dq_r = std::make_shared<op::Dequantize>(
            q_summand, summand_scale, uint8_zero, element::f32, AxisSet{});
        auto r_r = std::make_shared<op::Reshape>(dq_r, AxisVector{0, 1, 2, 3}, Shape{1, 2, 2});
        auto b_r = std::make_shared<op::Broadcast>(r_r, Shape{1, 1, 2, 2}, AxisSet{0});
        auto add = b_l + b_r;
        auto relu = std::make_shared<op::Relu>(add);
        return make_shared<Function>(NodeVector{relu},
                                     ParameterVector{input, weights, bias, summand});
    };

    auto cpu_f1 = make_function();
    auto cpu_f2 = make_function();

    test::Uniform<float> rng(2.0f, 2.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : cpu_f1->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    // Disable CPUQuantFusion
    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:0", 1);
    auto cpu1_results = execute(cpu_f1, args, "CPU");
    // Enable CPUQuantFusion
    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:1", 1);
    auto cpu2_results = execute(cpu_f2, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu1_results.at(0), cpu2_results.at(0)));
}
Pruthvi's avatar
Pruthvi committed
3514

3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628
TEST(cpu_quant_fusion, qconvba_q)
{
    auto make_function = []() {
        Shape shape_input{1, 2, 2, 2};
        Shape shape_weights{1, 2, 1, 1};
        Shape shape_summand{1, 1, 2, 2};
        auto input_l = std::make_shared<op::Parameter>(element::f32, shape_input);
        auto weights_l = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto bias_l = std::make_shared<op::Parameter>(element::f32, Shape{shape_weights[0]});
        auto input_r = std::make_shared<op::Parameter>(element::f32, shape_input);
        auto weights_r = std::make_shared<op::Parameter>(element::f32, shape_weights);
        auto bias_r = std::make_shared<op::Parameter>(element::f32, Shape{shape_weights[0]});

        auto input_scale_l = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto weights_scale_l = op::Constant::create(element::f32, Shape{}, {2.0f});
        auto output_scale_l = op::Constant::create(element::f32, Shape{}, {4.0f});
        auto input_scale_r = op::Constant::create(element::f32, Shape{}, {5.0f});
        auto weights_scale_r = op::Constant::create(element::f32, Shape{}, {5.0f});
        auto output_scale_r = op::Constant::create(element::f32, Shape{}, {20.0f});

        auto int8_zero = op::Constant::create(element::i8, Shape{}, {0});
        auto int32_zero = op::Constant::create(element::i32, Shape{}, {0});
        auto uint8_zero = op::Constant::create(element::u8, Shape{}, {0});

        op::Quantize::RoundMode round_mode = op::Quantize::RoundMode::ROUND_NEAREST_TOWARD_EVEN;
        auto q_input_l = std::make_shared<op::Quantize>(
            input_l, input_scale_l, uint8_zero, element::u8, AxisSet{}, round_mode);
        auto q_weights_l = std::make_shared<op::Quantize>(
            weights_l, weights_scale_l, int8_zero, element::i8, AxisSet{}, round_mode);
        auto q_bias_l = std::make_shared<op::Quantize>(bias_l,
                                                       input_scale_l * weights_scale_l,
                                                       int32_zero,
                                                       element::i32,
                                                       AxisSet{},
                                                       round_mode);
        auto q_input_r = std::make_shared<op::Quantize>(
            input_r, input_scale_r, uint8_zero, element::u8, AxisSet{}, round_mode);
        auto q_weights_r = std::make_shared<op::Quantize>(
            weights_r, weights_scale_r, int8_zero, element::i8, AxisSet{}, round_mode);
        auto q_bias_r = std::make_shared<op::Quantize>(bias_r,
                                                       input_scale_r * weights_scale_r,
                                                       int32_zero,
                                                       element::i32,
                                                       AxisSet{},
                                                       round_mode);

        // Left Graph
        auto requant_scale_l = (input_scale_l * weights_scale_l) / output_scale_l;
        auto conv_l = std::make_shared<op::QuantizedConvolutionBias>(q_input_l,
                                                                     q_weights_l,
                                                                     q_bias_l,
                                                                     Strides{1, 1},
                                                                     Strides{1, 1},
                                                                     CoordinateDiff{0, 0},
                                                                     CoordinateDiff{0, 0},
                                                                     Strides{1, 1},
                                                                     requant_scale_l);
        auto dq_l = std::make_shared<op::Dequantize>(
            conv_l, output_scale_l, int8_zero, element::f32, AxisSet{});
        auto r_l = std::make_shared<op::Reshape>(dq_l, AxisVector{0, 1, 2, 3}, Shape{1, 2, 2});
        auto b_l = std::make_shared<op::Broadcast>(r_l, Shape{1, 1, 2, 2}, AxisSet{0});

        // Right Graph
        auto requant_scale_r = (input_scale_r * weights_scale_r) / output_scale_r;
        auto conv_r = std::make_shared<op::QuantizedConvolutionBias>(q_input_r,
                                                                     q_weights_r,
                                                                     q_bias_r,
                                                                     Strides{1, 1},
                                                                     Strides{1, 1},
                                                                     CoordinateDiff{0, 0},
                                                                     CoordinateDiff{0, 0},
                                                                     Strides{1, 1},
                                                                     requant_scale_r);
        auto dq_r = std::make_shared<op::Dequantize>(
            conv_r, output_scale_r, int8_zero, element::f32, AxisSet{});
        auto r_r = std::make_shared<op::Reshape>(dq_r, AxisVector{0, 1, 2, 3}, Shape{1, 2, 2});
        auto b_r = std::make_shared<op::Broadcast>(r_r, Shape{1, 1, 2, 2}, AxisSet{0});
        auto add = b_l + b_r;
        auto relu = std::make_shared<op::Relu>(add);
        auto q = std::make_shared<op::Quantize>(
            relu, output_scale_r, uint8_zero, element::u8, AxisSet{}, round_mode);
        auto dq = std::make_shared<op::Dequantize>(
            q, output_scale_r, uint8_zero, element::f32, AxisSet{});
        return make_shared<Function>(
            NodeVector{dq},
            ParameterVector{input_l, weights_l, bias_l, input_r, weights_r, bias_r});
    };

    auto cpu_f1 = make_function();
    auto cpu_f2 = make_function();

    test::Uniform<float> rng(2.0f, 2.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : cpu_f1->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    // Disable CPUQuantFusion
    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:0", 1);
    auto cpu1_results = execute(cpu_f1, args, "CPU");
    // Enable CPUQuantFusion
    set_environment("NGRAPH_PASS_ENABLES", "CPUQuantFusion:1", 1);
    auto cpu2_results = execute(cpu_f2, args, "CPU");
    EXPECT_TRUE(test::all_close(cpu1_results.at(0), cpu2_results.at(0)));

    auto backend = runtime::Backend::create("CPU");
    auto fuse = make_function();
    backend->compile(fuse);
    ASSERT_EQ(count_ops_of_type<op::Quantize>(fuse), 6);
}

3629
#ifndef NGRAPH_JSON_DISABLE
3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651
// Tests that rely on deserializing json files
TEST(cpu_fusion, fuse_conv_bias)
{
    pass::Manager pass_manager;
    pass_manager.register_pass<ngraph::pass::ReshapeElimination>();
    pass_manager.register_pass<ngraph::runtime::cpu::pass::CPUFusion>();
    const string json_path = file_util::path_join(SERIALIZED_ZOO, "conv_bias.json");
    const string json_string = file_util::read_file_to_string(json_path);
    stringstream ss(json_string);
    shared_ptr<Function> func = ngraph::deserialize(ss);
    pass_manager.run_passes(func);
    size_t cb = count_ops_of_type<op::ConvolutionBias>(func);
    ASSERT_GT(cb, 0);
}

TEST(cpu_fusion, gemm_mlp)
{
    const string json_path = file_util::path_join(SERIALIZED_ZOO, "mxnet/mnist_mlp_forward.json");
    const string json_string = file_util::read_file_to_string(json_path);
    stringstream ss(json_string);
    shared_ptr<Function> func = ngraph::deserialize(ss);
    pass::Manager pass_manager;
3652
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
3653 3654 3655 3656 3657 3658 3659 3660 3661 3662
    pass_manager.run_passes(func);
    auto mmbs = count_ops_of_type<op::MatmulBias>(func);
    ASSERT_EQ(mmbs, 3);
}

TEST(cpu_fusion, fuse_fprop_bn)
{
    pass::Manager pass_manager;
    pass_manager.register_pass<pass::VisualizeTree>("bn_fprop_before_fusion.png");
    pass_manager.register_pass<ngraph::pass::ReshapeElimination>();
3663
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781
    pass_manager.register_pass<pass::VisualizeTree>("bn_fprop_after_fusion.png");
    const string json_path = file_util::path_join(SERIALIZED_ZOO, "mxnet/bn_fprop_b2c3h2w2.json");
    const string json_string = file_util::read_file_to_string(json_path);
    stringstream ss(json_string);
    shared_ptr<Function> func = ngraph::deserialize(ss);
    pass_manager.run_passes(func);
    size_t ccg = count_ops_of_type<op::BatchNormTraining>(func);
    ASSERT_EQ(ccg, 1);
}

TEST(cpu_fusion, sigmoid_multiply_fusion)
{
    pass::Manager pass_manager;
    pass_manager.register_pass<pass::CoreFusion>();
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>();
    const string json_path = file_util::path_join(SERIALIZED_ZOO, "mxnet/3_lstm_cell_forward.json");
    const string json_string = file_util::read_file_to_string(json_path);
    stringstream ss(json_string);
    shared_ptr<Function> func = ngraph::deserialize(ss);
    pass_manager.run_passes(func);
    size_t ccg = count_ops_of_type<op::SigmoidMultiply>(func);
    ASSERT_EQ(ccg, 18);
}

TEST(cpu_fusion, fuse_batch_mat_mul_transpose)
{
    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUBatchFusion>();
    const string json_path = file_util::path_join(SERIALIZED_ZOO, "mxnet/batch_dot_3.json");
    const string json_string = file_util::read_file_to_string(json_path);
    stringstream ss(json_string);
    shared_ptr<Function> func = ngraph::deserialize(ss);
    pass_manager.run_passes(func);
    size_t ccg = count_ops_of_type<op::BatchMatMulTranspose>(func);
    ASSERT_EQ(ccg, 1);
}

TEST(cpu_fusion, fuse_batch_mat_mul_transpose_forward)
{
    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUBatchFusion>();

    const std::string file_name("mxnet/batch_dot_3.json");
    auto cpu_f = make_function_from_file(file_name);
    auto int_f = make_function_from_file(file_name);
    pass_manager.run_passes(cpu_f);
    test::Uniform<float> rng(0.0f, 1.0f);
    vector<vector<float>> args;

    for (shared_ptr<op::Parameter> param : int_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    for (size_t i = 0; i < int_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f));
    }
}

TEST(cpu_fusion, fuse_batch_dot_backward)
{
    const std::string file_name("mxnet/batch_dot_3.json");
    auto cpu_f = make_function_from_file(file_name);
    auto int_f = make_function_from_file(file_name);

    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUBatchFusion>();
    pass_manager.run_passes(cpu_f);

    auto int_df = autodiff::backprop_function(int_f);
    auto cpu_df = autodiff::backprop_function(cpu_f);

    test::Uniform<float> rng(-1.0f, 1.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : cpu_df->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    auto int_results = execute(int_df, args, "INTERPRETER");
    auto cpu_results = execute(cpu_df, args, "CPU");

    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f));
    }
}

TEST(cpu_fusion, fuse_rnn_across_layer_2layer_3timestep)
{
    const std::string file_name("mxnet/2layer_3timestep_ic100oc100.json");
    auto cpu_f = make_function_from_file(file_name);
    auto int_f = make_function_from_file(file_name);
    test::Uniform<float> rng(-1.0f, 1.0f);
    vector<vector<float>> args;

    for (shared_ptr<op::Parameter> param : int_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");

    EXPECT_EQ(1, count_ops_of_type<op::Rnn>(cpu_f));
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f));
    }
}

Pruthvi's avatar
Pruthvi committed
3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823
TEST(cpu_fusion, fuse_bi_directional_rnn)
{
    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::LSTMFusion>();
    pass_manager.register_pass<runtime::cpu::pass::RNNFusion>();
    pass_manager.register_pass<ngraph::pass::AlgebraicSimplification>();
    pass_manager.register_pass<runtime::cpu::pass::MultiLayerRNNFusion>();
    pass_manager.register_pass<runtime::cpu::pass::BiDirectionalRnn>();
    const string json_path = file_util::path_join(SERIALIZED_ZOO, "mxnet/lstm_bi_directional.json");
    const string json_string = file_util::read_file_to_string(json_path);
    stringstream ss(json_string);
    shared_ptr<Function> func = ngraph::deserialize(ss);
    pass_manager.run_passes(func);
    // Bidirectional graph pass will folds the reverse seq
    auto rev_seq_ops = get_ops_of_type<op::Reverse>(func);
    auto rnn_ops = get_ops_of_type<op::Rnn>(func);
    EXPECT_EQ(rev_seq_ops.size(), 0);
    // fuse two bi-directional rnn layers in to one MKLDNN Op
    EXPECT_EQ(rnn_ops.size(), 1);
}

TEST(cpu_fusion, bi_rnn_interpreter_vs_cpu)
{
    const std::string file_name("mxnet/lstm_bi_directional.json");
    auto cpu_f = make_function_from_file(file_name);
    auto int_f = make_function_from_file(file_name);
    test::Uniform<float> rng(0.0f, 1.0f);
    vector<vector<float>> args;

    for (shared_ptr<op::Parameter> param : int_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    for (size_t i = 0; i < int_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f));
    }
}
3824 3825 3826 3827 3828

TEST(cpu_fusion, rnn_fusion_from_json_model)
{
    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPURnnMatFusion>();
3829
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840
    const string json_path =
        file_util::path_join(SERIALIZED_ZOO, "mxnet/rnn-10-step-fusion-test.json");
    const string json_string = file_util::read_file_to_string(json_path);
    stringstream ss(json_string);
    shared_ptr<Function> func = ngraph::deserialize(ss);
    pass_manager.run_passes(func);
    const size_t NUM_STEPS = 10;
    auto mmb_predicate = [=](std::shared_ptr<Node> node) {
        auto users = node->get_users();
        return (users.size() == NUM_STEPS) &&
               std::all_of(begin(users), end(users), [](std::shared_ptr<Node> n) {
3841
                   return as_type_ptr<op::Slice>(n) != nullptr;
3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879
               });
    };

    auto mmbs = get_ops_of_type<op::MatmulBias>(func);
    ASSERT_TRUE(std::any_of(begin(mmbs), end(mmbs), mmb_predicate));
}

TEST(cpu_fusion, fuse_lstm_cells)
{
    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::LSTMFusion>();
    const string json_path =
        file_util::path_join(SERIALIZED_ZOO, "mxnet/2rnn_layer_3lstm_cell.json");
    const string json_string = file_util::read_file_to_string(json_path);
    stringstream ss(json_string);
    shared_ptr<Function> func = ngraph::deserialize(ss);
    pass_manager.run_passes(func);
    auto lstm_ops = get_ops_of_type<op::Lstm>(func);
    EXPECT_EQ(lstm_ops.size(), 6);
}

TEST(cpu_fusion, fuse_2_layer_rnn)
{
    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::LSTMFusion>();
    pass_manager.register_pass<runtime::cpu::pass::RNNFusion>();
    const string json_path =
        file_util::path_join(SERIALIZED_ZOO, "mxnet/2rnn_layer_3lstm_cell.json");
    const string json_string = file_util::read_file_to_string(json_path);
    stringstream ss(json_string);
    shared_ptr<Function> func = ngraph::deserialize(ss);
    pass_manager.run_passes(func);
    size_t count = count_ops_of_type<op::Rnn>(func);
    auto rnn_ops = get_ops_of_type<op::Rnn>(func);
    EXPECT_EQ(rnn_ops.size(), count);
    for (auto& node : rnn_ops)
    {
        EXPECT_EQ(node->get_num_timesteps(), node->get_src_sequence_length());
3880
#if MKLDNN_VERSION_MAJOR < 1
3881
        EXPECT_EQ(node->get_num_cell_states(), node->get_argument(1)->get_arguments().size());
3882
#endif
3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903
    }
}

TEST(cpu_fusion, fuse_1_layer_rnn)
{
    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::LSTMFusion>();
    pass_manager.register_pass<runtime::cpu::pass::RNNFusion>();
    const string json_path =
        file_util::path_join(SERIALIZED_ZOO, "mxnet/1rnn_layer_3lstm_cell.json");
    const string json_string = file_util::read_file_to_string(json_path);
    stringstream ss(json_string);
    shared_ptr<Function> func = ngraph::deserialize(ss);
    pass_manager.run_passes(func);
    size_t count = count_ops_of_type<op::Rnn>(func);
    auto rnn_ops = get_ops_of_type<op::Rnn>(func);
    EXPECT_EQ(rnn_ops.size(), 1);
    EXPECT_EQ(rnn_ops.size(), count);
    for (auto& node : rnn_ops)
    {
        EXPECT_EQ(node->get_num_timesteps(), node->get_src_sequence_length());
3904
#if MKLDNN_VERSION_MAJOR < 1
3905
        EXPECT_EQ(node->get_num_cell_states(), node->get_argument(1)->get_arguments().size());
3906
#endif
3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953
    }
}

TEST(cpu_fusion, rnn_fusion_1lstm_cell)
{
    const std::string file_name("mxnet/1_lstm_cell_forward.json");
    auto cpu_f = make_function_from_file(file_name);
    auto int_f = make_function_from_file(file_name);
    test::Uniform<float> rng(-1.0f, 1.0f);
    vector<vector<float>> args;

    for (shared_ptr<op::Parameter> param : int_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f));
    }
}

TEST(cpu_fusion, rnn_fusion_1rnn_layer_3lstm_cell)
{
    const std::string file_name("mxnet/1rnn_layer_3lstm_cell.json");
    auto cpu_f = make_function_from_file(file_name);
    auto int_f = make_function_from_file(file_name);
    test::Uniform<float> rng(-1.0f, 1.0f);
    vector<vector<float>> args;

    for (shared_ptr<op::Parameter> param : int_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f));
    }
}

3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969
TEST(cpu_fusion, lstm_cell)
{
    auto make_function = []() {
        const size_t batch_size = 3;
        const size_t input_size = 4;
        const size_t hidden_size = 4;
        const size_t gates_count = 4;

        const auto X = make_shared<op::Parameter>(element::f32, Shape{batch_size, input_size});
        const auto W =
            make_shared<op::Parameter>(element::f32, Shape{gates_count * hidden_size, input_size});
        const auto R =
            make_shared<op::Parameter>(element::f32, Shape{gates_count * hidden_size, hidden_size});
        const auto H_t = make_shared<op::Parameter>(element::f32, Shape{batch_size, hidden_size});
        const auto C_t = make_shared<op::Parameter>(element::f32, Shape{batch_size, hidden_size});

3970
        const auto lstm_cell = make_shared<op::LSTMCell>(X, H_t, C_t, W, R, hidden_size);
3971 3972 3973
        auto ht = make_shared<op::GetOutputElement>(lstm_cell, 0);
        auto ct = make_shared<op::GetOutputElement>(lstm_cell, 1);

3974 3975 3976 3977
        auto lstm_function = make_shared<Function>(NodeVector{ht, ct},
                                                   ParameterVector{
                                                       X, H_t, C_t, W, R,
                                                   });
3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002
        return lstm_function;
    };
    auto lstm_function_cpu = make_function();
    auto lstm_function_inter = make_function();
    test::Uniform<float> rng(-1.0f, 1.0f);
    vector<vector<float>> args;

    for (shared_ptr<op::Parameter> param : lstm_function_cpu->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    auto int_results = execute(lstm_function_inter, args, "INTERPRETER");
    auto cpu_results = execute(lstm_function_cpu, args, "CPU");
    size_t lstm_op_count = count_ops_of_type<op::LSTMCell>(lstm_function_cpu);

    EXPECT_EQ(lstm_op_count, 0);
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f));
    }
}

4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024
TEST(cpu_fusion, rnn_fusion_2rnn_layer_3lstm_cell)
{
    const std::string file_name("mxnet/2rnn_layer_3lstm_cell.json");
    auto cpu_f = make_function_from_file(file_name);
    auto int_f = make_function_from_file(file_name);
    test::Uniform<float> rng(-1.0f, 1.0f);
    vector<vector<float>> args;

    for (shared_ptr<op::Parameter> param : int_f->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }
    auto int_results = execute(int_f, args, "INTERPRETER");
    auto cpu_results = execute(cpu_f, args, "CPU");
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f));
    }
}

4025
TEST(cpu_fusion, validate_fuse_gru_inputs)
4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046
{
    const std::string file_name("mxnet/gru_debug.json");
    auto cpu_func = make_function_from_file(file_name);
    auto int_func = make_function_from_file(file_name);

    test::Uniform<float> rng(-10.0f, 10.0f);
    vector<vector<float>> args;
    for (shared_ptr<op::Parameter> param : int_func->get_parameters())
    {
        vector<float> tensor_val(shape_size(param->get_shape()));
        rng.initialize(tensor_val);
        args.push_back(tensor_val);
    }

    auto int_results = execute(int_func, args, "INTERPRETER");
    auto cpu_results = execute(cpu_func, args, "CPU");
    for (size_t i = 0; i < cpu_results.size(); i++)
    {
        EXPECT_TRUE(test::all_close(cpu_results.at(i), int_results.at(i), 1.0e-4f, 1.0e-4f));
    }
}
4047

4048
#if defined(AUTODIFF_BACKEND_CPU) && !defined(NGRAPH_JSON_DISABLE)
4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070
NGRAPH_TEST(cpu_fusion, backwards_batchmatmultranspose_tensor2_tensor2)
{
    auto backend = runtime::Backend::create("CPU");

    const std::string file_name("mxnet/batch_dot_3.json");
    auto f = make_function_from_file(file_name);

    test::Uniform<float> rng(-1.0f, 1.0f);
    std::vector<std::shared_ptr<ngraph::runtime::Tensor>> args;
    for (shared_ptr<op::Parameter> param : f->get_parameters())
    {
        args.push_back(rng.initialize(backend->create_tensor<float>(param->get_shape())));
    }

    auto g = make_function_from_file(file_name);
    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUBatchFusion>();
    pass_manager.run_passes(g);
    EXPECT_TRUE(autodiff_numeric_compare<float>(backend.get(), f, g, args, .01f, .01f));
}
#endif

4071
#endif