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

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
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) {
115
        return static_cast<bool>(as_type_ptr<op::Reshape>(n));
116 117
    };

118 119
    auto skip_w = std::make_shared<pattern::op::Skip>(W, reshape_pred);
    auto skip_x = std::make_shared<pattern::op::Skip>(x, reshape_pred);
120 121 122 123 124 125

    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;

126
    TestMatcher n;
127 128 129 130 131 132 133 134 135 136 137 138 139 140
    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);

141 142 143 144 145 146 147 148 149 150 151 152
    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);

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

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

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

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

162 163 164
    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);
165 166 167 168 169 170

    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);

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

177 178 179 180 181 182 183 184
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);

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

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

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

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

194 195 196
    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);
197 198 199 200 201 202

    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);

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

TEST(cpu_fusion, gemm_cpu_broadcast_matrix)
210 211 212 213 214 215 216 217 218 219 220 221 222
{
    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});
223 224
    auto cg = make_shared<op::MatmulBias>(
        A, B, one, A->get_shape(), B->get_shape(), true, true, AxisSet{0, 1});
225

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

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

230 231 232
    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);
233 234 235 236 237 238

    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);

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

245 246 247 248 249 250 251 252 253 254 255
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});

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

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

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

263 264 265
    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);
266 267 268 269 270 271

    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);

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

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
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;
293
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
294
    auto func = make_shared<Function>(graph, ParameterVector{A, B, C});
295
    pass_manager.run_passes(func);
296
    ASSERT_NE(as_type_ptr<op::MatmulBias>(graph->get_argument(0)), nullptr);
297 298
}

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

    auto dot = make_shared<op::Dot>(A, B);
    auto graph = make_shared<op::Abs>(dot);
    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
    auto func = make_shared<Function>(graph, ParameterVector{A, B, C});
    pass_manager.run_passes(func);
    ASSERT_NE(as_type_ptr<op::MatmulBias>(graph->get_argument(0)), nullptr);
}

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
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;
333
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
334
    auto func = make_shared<Function>(graph, ParameterVector{A, B, C});
335
    pass_manager.run_passes(func);
336
    ASSERT_NE(as_type_ptr<op::MatmulBias>(graph->get_argument(0)), nullptr);
337 338
}

339 340 341 342 343 344 345 346 347 348
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>(
349
        W, x, Output<Node>(), W->get_shape(), x->get_shape(), false, false);
350 351 352 353 354
    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;
355
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
356
    auto func = make_shared<Function>(graph, ParameterVector{W, x, b});
357
    pass_manager.run_passes(func);
358
    auto gmm = graph->get_argument(0);
359
    ASSERT_TRUE(as_type_ptr<op::MatmulBias>(gmm));
360
    ASSERT_EQ(gmm->get_argument(2), b);
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
}

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;
376
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
377
    auto func = make_shared<Function>(graph, ParameterVector{W, x});
378 379 380 381 382
    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
383
struct ConvolutionBiasTestData
Louis Feng's avatar
Louis Feng committed
384
{
Louis Feng's avatar
Louis Feng committed
385 386 387 388 389 390
    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};
391 392 393 394 395 396 397 398
    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
399 400 401 402 403 404 405 406 407 408 409 410 411 412
    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;

413
    void n1c1h3w3(runtime::Backend* backend)
Louis Feng's avatar
Louis Feng committed
414
    {
Louis Feng's avatar
Louis Feng committed
415 416 417 418 419 420 421 422 423 424 425 426 427
        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
428
        result_shape = Shape{n, filter, 1, 1};
Louis Feng's avatar
Louis Feng committed
429

430
        data_val = backend->create_tensor(element::f32, data_shape);
Louis Feng's avatar
Louis Feng committed
431 432 433 434 435 436 437 438 439 440
        copy_data(data_val,
                  vector<float>{-0.67765152f,
                                0.10073948f,
                                0.57595438f,
                                -0.3469252f,
                                -0.22134334f,
                                -1.80471897f,
                                -0.80642909f,
                                1.22033095f,
                                2.23235631f});
441
        weights_val = backend->create_tensor(element::f32, weights_shape);
Louis Feng's avatar
Louis Feng committed
442 443 444 445 446 447 448 449 450 451
        copy_data(weights_val,
                  vector<float>{0.20070229f,
                                -0.54968649f,
                                -0.19819015f,
                                -0.38577855f,
                                1.37109005f,
                                -0.23789984f,
                                0.14867957f,
                                -0.49851316f,
                                -0.84815776f});
452
        bias_val = backend->create_tensor(element::f32, bias_shape);
Louis Feng's avatar
Louis Feng committed
453 454
        copy_data(bias_val, vector<float>{0.07811152f});

455
        result_val = backend->create_tensor(element::f32, result_shape);
Louis Feng's avatar
Louis Feng committed
456 457 458
        copy_data(result_val, vector<float>{0});

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

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

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

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

Louis Feng's avatar
Louis Feng committed
471
        expected_result_val = vector<float>{-2.58936238f};
Louis Feng's avatar
Louis Feng committed
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
        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
490
        expected_d_bias_val = vector<float>{-2.58936238f};
Louis Feng's avatar
Louis Feng committed
491
    }
Louis Feng's avatar
Louis Feng committed
492
};
Louis Feng's avatar
Louis Feng committed
493

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

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

    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
504
    auto f = make_shared<Function>(
505
        convolution_bias, ParameterVector{conv_test.data, conv_test.weights, conv_test.bias});
Louis Feng's avatar
Louis Feng committed
506

507
    auto handle = backend->compile(f);
508 509
    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
510
    auto result_vec = read_vector<float>(conv_test.result_val);
Louis Feng's avatar
Louis Feng committed
511

Louis Feng's avatar
Louis Feng committed
512 513
    EXPECT_TRUE(
        test::all_close(conv_test.expected_result_val, read_vector<float>(conv_test.result_val)));
Louis Feng's avatar
Louis Feng committed
514 515
}

Louis Feng's avatar
Louis Feng committed
516
TEST(cpu_fusion, conv_bias_bprop_n1c1h3w3)
Louis Feng's avatar
Louis Feng committed
517
{
518
    auto backend = runtime::Backend::create("CPU");
Louis Feng's avatar
Louis Feng committed
519

Louis Feng's avatar
Louis Feng committed
520
    ConvolutionBiasTestData conv_test;
521
    conv_test.n1c1h3w3(backend.get());
Louis Feng's avatar
Louis Feng committed
522 523 524 525

    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
526
    auto f = make_shared<Function>(
527
        convolution_bias, ParameterVector{conv_test.data, conv_test.weights, conv_test.bias});
Louis Feng's avatar
Louis Feng committed
528

529 530
    ngraph::autodiff::Adjoints adjoints(OutputVector{convolution_bias},
                                        OutputVector{conv_test.delta});
531

532 533 534
    auto d_data = adjoints.backprop_output(conv_test.data);
    auto d_weights = adjoints.backprop_output(conv_test.weights);
    auto d_bias = adjoints.backprop_output(conv_test.bias);
Louis Feng's avatar
Louis Feng committed
535

Louis Feng's avatar
Louis Feng committed
536
    auto df = make_shared<Function>(
537
        OutputVector{d_data, d_weights, d_bias},
538
        ParameterVector{conv_test.data, conv_test.weights, conv_test.bias, conv_test.delta});
539 540 541
    auto handle = backend->compile(df);
    handle->call_with_validate(

542 543
        {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
544

Louis Feng's avatar
Louis Feng committed
545 546 547 548 549 550
    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
551
}
Pruthvi's avatar
Pruthvi committed
552

553 554 555 556 557 558
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);
559 560
    auto bias = make_shared<op::Parameter>(element::f32, Shape{shape[0]});
    auto pbroadcast = std::make_shared<op::Broadcast>(bias, shape, AxisSet{1, 2, 3});
561 562 563 564 565
    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>();
566
    pass_manager.register_pass<pass::VisualizeTree>("conv_bias_bprop_fusion.png");
567
    auto f = make_shared<Function>(conv_bias, ParameterVector{data_batch, filters, bias});
568

569
    ngraph::autodiff::Adjoints adjoints(OutputVector{conv_bias}, OutputVector{delta});
570

571 572 573
    auto d_data = adjoints.backprop_output(data_batch);
    auto d_weights = adjoints.backprop_output(filters);
    auto d_bias = adjoints.backprop_output(bias);
574

575
    auto df = make_shared<Function>(OutputVector{d_data, d_weights, d_bias},
576
                                    ParameterVector{data_batch, filters, bias, delta});
577 578 579 580 581 582

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

583
static void test_batchnorm_multiply_add_relu(Shape input_shape)
Amy Zhuang's avatar
Amy Zhuang committed
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
{
    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};
601
        for (size_t i = 2; i < input_shape.size(); i++)
Amy Zhuang's avatar
Amy Zhuang committed
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
        {
            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();
624
    test::Uniform<float> rng(1.0f, 10.0f);
Amy Zhuang's avatar
Amy Zhuang committed
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
    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);
}

644
TEST(cpu_fusion, MLIR_DISABLE_TEST(batchnorm_multiply_add_relu))
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
{
    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;
670
        for (size_t i = 1; i < input_shape.size(); i++)
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
        {
            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);
}

713 714 715 716 717 718 719 720 721 722 723 724
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};
725
    auto bn = make_shared<op::BatchNormTraining>(input, gamma, beta, eps);
726 727 728 729 730 731 732 733 734 735 736 737 738

    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);

739
    auto bn_relu = make_shared<op::BatchNormTrainingRelu>(eps, gamma, beta, input);
740 741 742 743 744 745
    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},
746
        ParameterVector{input, gamma, beta});
747
    auto backend = runtime::Backend::create("CPU");
748 749

    // Create some tensors for input/output
750
    auto input_t = backend->create_tensor(element::f32, Shape{1, 2, 2, 2});
751 752 753 754 755 756 757 758 759 760

    copy_data(input_t,
              vector<float>{0.54881352f,
                            0.71518934f,
                            0.60276335f,
                            0.54488319f,
                            0.42365479f,
                            0.64589411f,
                            0.4375872f,
                            0.89177299f});
761
    auto gamma_t = backend->create_tensor(element::f32, gamma_shape);
762
    copy_data(gamma_t, vector<float>{1.0f, 1.0f});
763
    auto beta_t = backend->create_tensor(element::f32, beta_shape);
764
    copy_data(beta_t, vector<float>{0.0f, 0.0f});
765 766 767 768 769 770 771 772
    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);

773
    auto handle = backend->compile(f);
774 775 776 777 778 779 780
    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});
781 782 783 784 785 786 787 788

    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)));
}

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
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});
}

839 840 841 842 843 844 845 846
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)));
847
    auto func = make_shared<Function>(abs_node, ParameterVector{A, weights});
848 849

    pass::Manager pass_manager;
850
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
851 852 853 854 855
    pass_manager.run_passes(func);
    size_t cb = count_ops_of_type<op::ConvolutionRelu>(func);
    ASSERT_GT(cb, 0);
}

856
TEST(cpu_fusion, conv_relu_n2c1h2w2_2)
857 858 859 860
{
    Shape shape_a{2, 1, 6, 6};
    Shape shape_weights{1, 1, 2, 2};

861 862 863 864 865
    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);
866
        auto f = make_shared<Function>(NodeVector{relu}, ParameterVector{A, weights});
867 868
        return f;
    };
869

870
    auto int_f = make_int_function();
871

872 873 874 875 876
    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);
877
        auto f = make_shared<Function>(NodeVector{conv_relu}, ParameterVector{A, weights});
878 879
        return f;
    };
880

881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
    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)));
}
897

898 899 900 901 902 903 904 905 906 907 908 909 910 911
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);
912
        auto f = make_shared<Function>(NodeVector{relu}, ParameterVector{A, weights, bias});
913 914 915 916 917 918 919 920 921 922
        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});
923
        auto conv_bias_relu = std::make_shared<op::ConvolutionBias>(conv, bias, true);
924 925
        auto f =
            make_shared<Function>(NodeVector{conv_bias_relu}, ParameterVector{A, weights, bias});
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
        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)));
}

947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
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},
971
                                       ParameterVector{A, weights1, bias1, weights2, bias2});
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
        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);
}

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
// 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);

1014 1015
    return result_output ? make_shared<Function>(add, ParameterVector{A, weights, bias, B})
                         : make_shared<Function>(abs, ParameterVector{A, weights, bias, B});
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
}

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
1033
    ASSERT_EQ(count_ops_of_type<op::ConvolutionBiasAdd>(func_nofuse2), 1);
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
}

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
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
// 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);

1063 1064
    return result_output ? make_shared<Function>(add, ParameterVector{A, weights, B})
                         : make_shared<Function>(abs, ParameterVector{A, weights, B});
gaurides's avatar
gaurides committed
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
}

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)));
}

1106 1107 1108 1109 1110 1111 1112 1113 1114
#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)
{
1115
    Shape shape_a{2, 1, 600, 600};
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 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

    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
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
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)
{
1214
    bool use_deconv_fuse = (getenv_bool("NGRAPH_DECONV_FUSE"));
gaurides's avatar
gaurides committed
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 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
    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");
    }
}

1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
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},
1280
                                                        groups);
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291

    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 =
1292 1293
        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);
1294 1295 1296 1297
    if (with_relu)
    {
        auto prelu = std::make_shared<op::Relu>(bn);
        auto f = make_shared<Function>(NodeVector{prelu},
1298
                                       ParameterVector{input, weights, gamma, beta, mean, var});
1299 1300 1301 1302 1303
        return f;
    }
    else
    {
        auto f = make_shared<Function>(NodeVector{bn},
1304
                                       ParameterVector{input, weights, gamma, beta, mean, var});
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 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
        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);
}

1399 1400 1401 1402 1403 1404 1405 1406
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)
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
{
    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);
    }
1427
    auto func = make_shared<Function>(results, ParameterVector{data, weights, bias});
1428 1429 1430 1431
    if (enable_pass)
    {
        pass::Manager pass_manager;
        pass_manager.register_pass<runtime::cpu::pass::CPURnnMatFusion>();
1432 1433
        pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(
            pass::FusionType::REGULAR_FUSIONS);
1434 1435 1436 1437 1438 1439
        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);
    }

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

1442
    shared_ptr<runtime::Tensor> data_tensor =
1443
        backend->create_tensor(element::f32, data->get_shape());
1444
    shared_ptr<runtime::Tensor> weights_tensor =
1445
        backend->create_tensor(element::f32, weights->get_shape());
1446
    shared_ptr<runtime::Tensor> bias_tensor =
1447
        backend->create_tensor(element::f32, bias->get_shape());
1448

1449
    std::vector<shared_ptr<runtime::Tensor>> result_tensors;
1450 1451
    for (auto r : results)
    {
1452
        result_tensors.push_back(backend->create_tensor(element::f32, r->get_shape()));
1453 1454 1455 1456 1457
    }

    copy_data(data_tensor, data_val);
    copy_data(weights_tensor, weights_val);
    copy_data(bias_tensor, bias_val);
1458 1459
    auto handle = backend->compile(func);
    handle->call_with_validate(result_tensors, {data_tensor, weights_tensor, bias_tensor});
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
    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);

1478
    std::vector<shared_ptr<runtime::Tensor>> result_expected = rnn_matrix_fusion_eval(
1479
        time_steps, data_shape, weights_shape, bias_shape, data_val, weights_val, bias_val, false);
1480
    std::vector<shared_ptr<runtime::Tensor>> result_fused = rnn_matrix_fusion_eval(
1481 1482 1483 1484 1485 1486
        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]));
    }
}
1487

Nick Korovaiko's avatar
Nick Korovaiko committed
1488 1489 1490 1491 1492 1493
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});
1494
    auto tvt = &reshape_conv->output(0).get_tensor();
1495
    auto lt_desc = std::make_shared<runtime::cpu::LayoutDescriptor>(*tvt);
Nick Korovaiko's avatar
Nick Korovaiko committed
1496 1497 1498 1499 1500 1501 1502
    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});
1503
    auto tvt_bprop = &reshape_conv_bprop->output(0).get_tensor();
1504
    auto lt_desc_bprop = std::make_shared<runtime::cpu::LayoutDescriptor>(*tvt_bprop);
Nick Korovaiko's avatar
Nick Korovaiko committed
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
    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},
1520
                                   ParameterVector{param, data_conv, dummy_arg_conv_bprop});
Nick Korovaiko's avatar
Nick Korovaiko committed
1521 1522 1523 1524 1525 1526 1527 1528

    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);

1529
    ASSERT_EQ(as_type_ptr<runtime::cpu::op::ConvertLayout>(new_convert_layout->get_argument(0)),
Nick Korovaiko's avatar
Nick Korovaiko committed
1530 1531
              cvt_lt_conv);
}
1532 1533 1534 1535 1536 1537 1538 1539 1540

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());

1541
    ngraph::autodiff::Adjoints adjoints(ngraph::OutputVector{max_pool}, ngraph::OutputVector{C});
1542

1543
    auto dinput = adjoints.backprop_output(input);
1544

1545
    auto df = std::make_shared<Function>(OutputVector{dinput}, ParameterVector{input, C});
1546

1547
    auto f = std::make_shared<Function>(NodeVector{max_pool}, ParameterVector{input});
1548 1549

    {
1550
        NodeVector nv_cwi;
1551
        pass::Manager pass_manager;
1552
        pass_manager.register_pass<runtime::cpu::pass::CPUWorkspaceInsertion>(nv_cwi);
1553 1554 1555 1556
        pass_manager.run_passes(df);
    }

    auto maxpool_goe_output =
1557
        as_type_ptr<op::GetOutputElement>(f->get_results().at(0)->get_argument(0));
1558 1559 1560 1561
    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 =
1562
        as_type_ptr<op::GetOutputElement>(maxpool_with_indices->get_argument(2));
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
    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);
1575
    auto f = std::make_shared<Function>(maxpool, ParameterVector{A});
1576 1577

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

1581 1582
    shared_ptr<runtime::Tensor> input = backend->create_tensor(element::f32, shape_a);
    shared_ptr<runtime::Tensor> output = backend->create_tensor(element::f32, shape_a);
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604

    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);

    {
1605
        NodeVector nv_cwi;
1606
        pass::Manager pass_manager;
1607
        pass_manager.register_pass<pass::VisualizeTree>("max_pool_bprop_before2.png");
1608
        pass_manager.register_pass<runtime::cpu::pass::CPUWorkspaceInsertion>(nv_cwi);
1609
        pass_manager.register_pass<pass::VisualizeTree>("max_pool_bprop_after2.png");
1610 1611 1612
        pass_manager.run_passes(df);
    }

1613
    auto handle = backend->compile(df);
1614
    handle->call_with_validate({output}, {input, ep});
1615
    EXPECT_TRUE(test::all_close_f(read_vector<float>(output), expected, MIN_FLOAT_TOLERANCE_BITS));
1616
}
1617

1618 1619 1620 1621 1622 1623 1624 1625
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);
1626
    return std::make_shared<Function>(NodeVector{max_pool, neg, absn}, ParameterVector{input});
1627 1628
}

1629
static std::pair<std::shared_ptr<ngraph::Function>, OutputVector>
1630 1631 1632 1633 1634
    make_backward_function(std::shared_ptr<ngraph::Function> f)
{
    // get parameters
    std::vector<std::shared_ptr<ngraph::op::Parameter>> back_parameters = f->get_parameters();

1635 1636
    ngraph::OutputVector adjoints;
    ngraph::OutputVector outputs;
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
    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
1649
    OutputVector dYdXs(back_parameters.size());
1650 1651 1652
    transform(back_parameters.begin(),
              back_parameters.end(),
              dYdXs.begin(),
1653
              [&adjoint](const std::shared_ptr<Node>& X) { return adjoint.backprop_output(X); });
1654 1655 1656 1657

    // create the backward function
    std::vector<std::shared_ptr<ngraph::op::Parameter>> param_adjoints;
    for (auto n : adjoints)
1658
        param_adjoints.push_back(as_type_ptr<ngraph::op::Parameter>(n.get_node_shared_ptr()));
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
    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);
1672
    pass_manager.register_pass<pass::VisualizeTree>("before.fprop_cache.png");
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 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722

    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);
1723
    auto fprop_cache = ngraph::cache_fprop(f, maybe_bf);
1724 1725

    auto mpwi_bprop = fprop_cache.bprop->get_results().at(0)->get_argument(0);
1726 1727
    ASSERT_TRUE(as_type_ptr<op::Parameter>(mpwi_bprop->get_argument(0)));
    ASSERT_TRUE(as_type_ptr<op::Parameter>(mpwi_bprop->get_argument(2)));
1728 1729
}

1730
TEST(cpu_fusion, conv_batch_norm_folding)
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
{
    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});
1745
        auto bn = std::make_shared<op::BatchNormInference>(conv, gamma, beta, mean, var, eps);
1746
        auto f = make_shared<Function>(NodeVector{bn},
1747
                                       ParameterVector{input, weights, gamma, beta, mean, var});
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
        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)));
}
1788

1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
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});
1807
        auto bn = std::make_shared<op::BatchNormInference>(convbias, gamma, beta, mean, var, eps);
1808
        auto f = make_shared<Function>(
1809
            NodeVector{bn}, ParameterVector{input, weights, bias, gamma, beta, mean, var});
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
        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)
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
{
    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}));
1847
        auto f = make_shared<Function>(NodeVector{out}, ParameterVector{input, weights, a, b});
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
        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)));
}

1887
TEST(cpu_fusion, convbias_affine_folding1)
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
{
    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 =
1908
            make_shared<Function>(NodeVector{out}, ParameterVector{input, weights, bias, a, b});
1909 1910 1911
        return f;
    };

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 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
    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);

1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
    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)));
}

1983
TEST(batch_fusion, group_convolution)
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
{
    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},
2001
                                                        GROUPS);
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025

    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},
2026
                                   ParameterVector{A, B, C, D, E, F});
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036

    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_);
2037 2038
    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
2039 2040

    auto e_ =
2041
        backend->create_tensor(element::f32, shape_c, av.data() + av.size() / 2); // lower weights
2042
    auto f_ =
2043
        backend->create_tensor(element::f32, shape_d, bv.data() + bv.size() / 2); // upper weights
2044 2045

    Shape shape_ur{1, 1, 2, 2};
2046
    // allocate a contigious storage for both lower and upper halves.
2047 2048 2049 2050 2051
    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));
2052 2053 2054
    auto handle = backend->compile(f);
    handle->call_with_validate({group_result, lower_result, upper_result},
                               {a_, b_, c_, d_, e_, f_});
2055
    EXPECT_TRUE(test::all_close_f(rv, erv));
2056 2057
}

2058
#if MKLDNN_VERSION_MAJOR < 1
2059 2060 2061 2062
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});
2063 2064
    auto weights_layer = make_shared<op::Parameter>(element::f32, Shape{100, 400});
    auto weights_iter = make_shared<op::Parameter>(element::f32, Shape{100, 400});
2065 2066 2067 2068 2069 2070 2071
    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
2072 2073 2074
    ngraph::runtime::cpu::rnn_utils::rnntype rnn_type =
        ngraph::runtime::cpu::rnn_utils::rnntype::vanilla_lstm;

2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
    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
2085 2086 2087
                                         num_of_rnn_fused_layer,
                                         rnn_type);

2088 2089 2090 2091 2092
    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},
2093
        ParameterVector{src_layer, src_iter, weights_layer, weights_iter, biases});
2094 2095
    auto backend = runtime::Backend::create("CPU");

2096
    shared_ptr<runtime::Tensor> src_layer_t =
2097
        backend->create_tensor(element::f32, src_layer->get_shape());
2098
    shared_ptr<runtime::Tensor> src_iter_t =
2099
        backend->create_tensor(element::f32, src_iter->get_shape());
2100
    shared_ptr<runtime::Tensor> weights_layer_t =
2101
        backend->create_tensor(element::f32, weights_layer->get_shape());
2102
    shared_ptr<runtime::Tensor> weights_iter_t =
2103
        backend->create_tensor(element::f32, weights_iter->get_shape());
2104
    shared_ptr<runtime::Tensor> biases_t =
2105
        backend->create_tensor(element::f32, biases->get_shape());
2106
    shared_ptr<runtime::Tensor> result_ht = backend->create_tensor(element::f32, {10, 100});
2107
    shared_ptr<runtime::Tensor> result_ct = backend->create_tensor(element::f32, Shape{20, 100});
2108 2109 2110 2111 2112 2113 2114

    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));

2115 2116
    auto handle = backend->compile(func);
    handle->call_with_validate(
2117 2118
        {result_ht, result_ct},
        {src_layer_t, src_iter_t, weights_layer_t, weights_iter_t, biases_t});
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
    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)));
}
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 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
#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
2209

2210
void sigmoid_multiply_fusion_forward_compute(runtime::Backend* backend,
2211
                                             const ParameterVector& input_params,
2212 2213 2214 2215 2216 2217 2218
                                             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)
{
2219
    shared_ptr<runtime::Tensor> result_tensor = backend->create_tensor(element::f32, result_shape);
2220

2221
    vector<shared_ptr<runtime::Tensor>> input_tensors;
2222
    for (size_t i = 0; i < input_params.size(); ++i)
2223 2224 2225 2226 2227 2228 2229
    {
        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);
2230
    auto handle = backend->compile(func);
2231
    handle->call_with_validate({result_tensor}, input_tensors);
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
    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};
2252
        ParameterVector input_params{input_0_param, input_1_param, input_2_param};
2253 2254
        vector<vector<float>> input_data{input_0_data, input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape, data_shape};
2255
        sigmoid_multiply_fusion_forward_compute(backend.get(),
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
                                                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};
2270
        ParameterVector input_params{input_0_param, input_1_param};
2271 2272
        vector<vector<float>> input_data{input_0_data, const_data};
        vector<Shape> input_shapes{data_shape, const_shape};
2273
        sigmoid_multiply_fusion_forward_compute(backend.get(),
2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287
                                                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};
2288
        ParameterVector input_params{input_0_param, input_1_param};
2289 2290
        vector<vector<float>> input_data{input_0_data, const_data};
        vector<Shape> input_shapes{data_shape, const_shape};
2291
        sigmoid_multiply_fusion_forward_compute(backend.get(),
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
                                                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};
2306
        ParameterVector input_params{input_0_param, input_1_param};
2307 2308
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2309
        sigmoid_multiply_fusion_forward_compute(backend.get(),
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
                                                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};
2324
        ParameterVector input_params{input_0_param, input_1_param};
2325 2326
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2327
        sigmoid_multiply_fusion_forward_compute(backend.get(),
2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
                                                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};
2342
        ParameterVector input_params{input_0_param, input_1_param};
2343 2344
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2345
        sigmoid_multiply_fusion_forward_compute(backend.get(),
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
                                                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};
2360
        ParameterVector input_params{input_0_param, input_1_param};
2361 2362
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2363
        sigmoid_multiply_fusion_forward_compute(backend.get(),
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373
                                                input_params,
                                                input_data,
                                                input_shapes,
                                                data_shape,
                                                sigmoid_0,
                                                sigmoid_1,
                                                expected);
    }
}

2374
void sigmoid_multiply_fusion_backward_compute(runtime::Backend* backend,
2375
                                              const ParameterVector& input_params,
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
                                              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)
{
2389
    vector<shared_ptr<runtime::Tensor>> input_tensors;
2390
    for (size_t i = 0; i < input_params.size(); ++i)
2391 2392 2393 2394 2395 2396
    {
        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);
2397
    shared_ptr<runtime::Tensor> delta_tensor = backend->create_tensor(element::f32, delta_shape);
2398 2399
    copy_data(delta_tensor, delta_data);

2400
    ParameterVector back_params(input_params);
2401 2402 2403
    back_params.push_back(delta_param);
    input_tensors.push_back(delta_tensor);

2404
    shared_ptr<runtime::Tensor> d_input_0_tensor =
2405
        backend->create_tensor(element::f32, d_input_0_shape);
2406
    shared_ptr<runtime::Tensor> d_input_1_tensor =
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420
        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);

2421
    ngraph::autodiff::Adjoints adjoints(OutputVector{sigmoid_mul}, OutputVector{delta_param});
2422 2423 2424
    auto d_input_0 = adjoints.backprop_output(input_0_adjoint);
    auto d_input_1 = adjoints.backprop_output(input_1_adjoint);
    auto df = make_shared<Function>(OutputVector{d_input_0, d_input_1}, back_params);
2425 2426
    auto handle = backend->compile(df);
    handle->call_with_validate({d_input_0_tensor, d_input_1_tensor}, input_tensors);
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450
    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};
2451
        ParameterVector input_params{input_0_param, input_1_param, input_2_param};
2452 2453
        vector<vector<float>> input_data{input_0_data, input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape, data_shape};
2454
        sigmoid_multiply_fusion_backward_compute(backend.get(),
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475
                                                 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};
2476
        ParameterVector input_params{input_0_param, input_1_param};
2477 2478
        vector<vector<float>> input_data{input_0_data, const_data};
        vector<Shape> input_shapes{data_shape, const_shape};
2479
        sigmoid_multiply_fusion_backward_compute(backend.get(),
2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500
                                                 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};
2501
        ParameterVector input_params{input_0_param, input_1_param};
2502 2503
        vector<vector<float>> input_data{input_0_data, const_data};
        vector<Shape> input_shapes{data_shape, const_shape};
2504
        sigmoid_multiply_fusion_backward_compute(backend.get(),
2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
                                                 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};
2526
        ParameterVector input_params{input_0_param, input_1_param};
2527 2528
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2529
        sigmoid_multiply_fusion_backward_compute(backend.get(),
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550
                                                 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};
2551
        ParameterVector input_params{input_0_param, input_1_param};
2552 2553
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2554
        sigmoid_multiply_fusion_backward_compute(backend.get(),
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575
                                                 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};
2576
        ParameterVector input_params{input_0_param, input_1_param};
2577 2578
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2579
        sigmoid_multiply_fusion_backward_compute(backend.get(),
2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600
                                                 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};
2601
        ParameterVector input_params{input_0_param, input_1_param};
2602 2603
        vector<vector<float>> input_data{input_0_data, input_1_data};
        vector<Shape> input_shapes{data_shape, data_shape};
2604
        sigmoid_multiply_fusion_backward_compute(backend.get(),
2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
                                                 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);
    }
}
2620

2621
static void check_bounded_relu(Shape param_shape, float constant_val)
2622
{
2623 2624 2625 2626 2627 2628 2629 2630 2631
    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;
    };
2632

2633 2634 2635
    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);
2636 2637 2638 2639 2640 2641 2642 2643 2644 2645
    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");
2646 2647 2648

    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));
2649
}
2650

2651
TEST(cpu_fusion, MLIR_DISABLE_TEST(fuse_bounded_relu_inter_vs_cpu))
2652
{
2653 2654 2655 2656
    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);
}
2657

2658
TEST(cpu_fusion, MLIR_DISABLE_TEST(fuse_dropout))
gaurides's avatar
gaurides committed
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 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729
{
    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
    }
}

2730
TEST(cpu_fusion, MLIR_DISABLE_TEST(fuse_leaky_relu))
2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747
{
    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);
2748 2749
    EXPECT_EQ(0, count_ops_of_type<op::CPULeakyRelu>(no_fuse1));
    EXPECT_EQ(0, count_ops_of_type<op::CPULeakyRelu>(no_fuse2));
2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760

    // 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");
2761
    EXPECT_EQ(1, count_ops_of_type<op::CPULeakyRelu>(cpu_f1));
2762 2763 2764
    EXPECT_TRUE(test::all_close(cpu1_results.at(0), expected_result));

    auto cpu2_results = execute(cpu_f2, args, "CPU");
2765
    EXPECT_EQ(1, count_ops_of_type<op::CPULeakyRelu>(cpu_f2));
2766 2767 2768
    EXPECT_TRUE(test::all_close(cpu2_results.at(0), expected_result));
}

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 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963
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)));
    }
}

2964 2965 2966 2967 2968 2969 2970 2971 2972
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);
2973
        return make_shared<Function>(dot, ParameterVector{a, b});
2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993
    };
    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));
    }
}
2994

Pruthvi's avatar
Pruthvi committed
2995
static std::shared_ptr<Function>
2996
    create_rnn_input_linear_transformation_function(size_t num_timesteps, bool data_is_4d = false)
Pruthvi's avatar
Pruthvi committed
2997 2998 2999
{
    auto W = std::make_shared<op::Parameter>(element::f32, Shape{400, 50});
    auto bias = std::make_shared<op::Parameter>(element::f32, Shape{400});
3000
    ParameterVector params{W, bias};
Pruthvi's avatar
Pruthvi committed
3001
    auto create_graph = [&]() -> std::shared_ptr<Node> {
3002 3003 3004
        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
3005
        params.push_back(data_param);
3006
        auto reshape_axis_order = data_is_4d ? AxisVector{0, 1, 2, 3} : AxisVector{0, 1, 2};
Pruthvi's avatar
Pruthvi committed
3007
        auto data_param_reshape =
3008
            std::make_shared<op::Reshape>(data_param, reshape_axis_order, Shape{10, 50});
Pruthvi's avatar
Pruthvi committed
3009 3010 3011 3012
        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);
3013
        return move(add_bias);
Pruthvi's avatar
Pruthvi committed
3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036
    };

    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);
}

3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048
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
3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069
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));
    }
}
3070

3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095
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},
3096 3097 3098 3099 3100 3101 3102
                                                               input_scale,
                                                               uint8_zero,
                                                               weights_scale,
                                                               int8_zero,
                                                               output_scale,
                                                               int8_zero,
                                                               element::i8,
3103 3104
                                                               AxisSet{},
                                                               AxisSet{},
3105
                                                               AxisSet{});
3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134
        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)));
}
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 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195
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)));
}

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 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271
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)));
}

3272
TEST(cpu_quant_fusion, MLIR_DISABLE_TEST(qconcat))
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 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319
{
    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
3320
    ASSERT_EQ(count_ops_of_type<op::Concat>(cpu_f2), 6);
3321 3322 3323
    EXPECT_TRUE(test::all_close(cpu1_results.at(0), cpu2_results.at(0)));
}

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 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533
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
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 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648
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);
}

3649
#ifndef NGRAPH_JSON_DISABLE
3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671
// 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;
3672
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
3673 3674 3675 3676 3677 3678 3679 3680 3681 3682
    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>();
3683
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707
    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);
}

3708
TEST(batch_fusion, fuse_batch_dot_backward)
3709 3710 3711 3712 3713 3714
{
    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;
3715
    pass_manager.register_pass<ngraph::pass::BatchFusion>();
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
    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
3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804
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));
    }
}
3805 3806 3807 3808 3809

TEST(cpu_fusion, rnn_fusion_from_json_model)
{
    pass::Manager pass_manager;
    pass_manager.register_pass<runtime::cpu::pass::CPURnnMatFusion>();
3810
    pass_manager.register_pass<runtime::cpu::pass::CPUFusion>(pass::FusionType::REGULAR_FUSIONS);
3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821
    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) {
3822
                   return as_type_ptr<op::Slice>(n) != nullptr;
3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860
               });
    };

    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());
3861
#if MKLDNN_VERSION_MAJOR < 1
3862
        EXPECT_EQ(node->get_num_cell_states(), node->get_argument(1)->get_arguments().size());
3863
#endif
3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884
    }
}

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());
3885
#if MKLDNN_VERSION_MAJOR < 1
3886
        EXPECT_EQ(node->get_num_cell_states(), node->get_argument(1)->get_arguments().size());
3887
#endif
3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 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
    }
}

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));
    }
}

3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950
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});

3951
        const auto lstm_cell = make_shared<op::LSTMCell>(X, H_t, C_t, W, R, hidden_size);
3952 3953 3954
        auto ht = make_shared<op::GetOutputElement>(lstm_cell, 0);
        auto ct = make_shared<op::GetOutputElement>(lstm_cell, 1);

3955 3956 3957 3958
        auto lstm_function = make_shared<Function>(NodeVector{ht, ct},
                                                   ParameterVector{
                                                       X, H_t, C_t, W, R,
                                                   });
3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983
        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));
    }
}

3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005
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));
    }
}

4006
TEST(cpu_fusion, validate_fuse_gru_inputs)
4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028
{
    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));
    }
}
#endif