backend_performance.cpp 8.52 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// ----------------------------------------------------------------------------
// Copyright 2017 Nervana Systems Inc.
// 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
// ----------------------------------------------------------------------------

#include <sstream>
#include <string>
#include <vector>

#include "gtest/gtest.h"

#include "ngraph/codegen/compiler.hpp"
#include "ngraph/codegen/execution_engine.hpp"
#include "ngraph/file_util.hpp"
#include "ngraph/log.hpp"
25
#include "ngraph/ops/concatenate.hpp"
26 27 28 29 30 31 32
#include "ngraph/runtime/backend.hpp"
#include "ngraph/runtime/call_frame.hpp"
#include "ngraph/runtime/cpu/cpu_call_frame.hpp"
#include "ngraph/runtime/manager.hpp"
#include "ngraph/serializer.hpp"
#include "ngraph/util.hpp"
#include "util/random.hpp"
33
#include "util/test_tools.hpp"
34 35 36 37

using namespace std;
using namespace ngraph;

38
static multimap<size_t, string>
39
    agregate_timing(const vector<runtime::PerformanceCounter>& perf_data)
40 41
{
    unordered_map<string, size_t> timing;
42
    for (const runtime::PerformanceCounter& p : perf_data)
43 44 45 46 47 48 49 50 51 52 53 54 55
    {
        string op = p.name().substr(0, p.name().find('_'));
        timing[op] += p.microseconds();
    }

    multimap<size_t, string> rc;
    for (const pair<string, size_t>& t : timing)
    {
        rc.insert({t.second, t.first});
    }
    return rc;
}

56
void run_benchmark(const string& json_path, const string& backend_name, size_t iterations)
57
{
58 59
    string env_var_name = "NGRAPH_" + backend_name + "_EMIT_TIMING";
    bool emit_timing = (std::getenv(env_var_name.c_str()) != nullptr);
60 61
    if (!emit_timing)
    {
62
        cout << "To get per-op timing set the environment variable " << env_var_name << "\n";
63 64
    }

65 66 67 68 69
    test::Uniform<float> rng{-1, 1, 0};
    const string json_string = file_util::read_file_to_string(json_path);
    stringstream ss(json_string);
    shared_ptr<Function> f = ngraph::deserialize(ss);

70 71
    stopwatch build_time;
    build_time.start();
72
    auto manager = runtime::Manager::get(backend_name);
73 74 75
    auto external = manager->compile(f);
    auto backend = manager->allocate_backend();
    auto cf = backend->make_call_frame(external);
76 77
    build_time.stop();
    cout << "build_time " << build_time.get_milliseconds() << "ms" << endl;
78

79
    vector<shared_ptr<runtime::TensorView>> args;
80 81
    for (shared_ptr<op::Parameter> param : f->get_parameters())
    {
82 83 84 85 86 87 88 89 90 91
        auto tensor =
            backend->make_primary_tensor_view(param->get_element_type(), param->get_shape());
        rng.initialize(tensor);
        args.push_back(tensor);
    }
    vector<shared_ptr<runtime::TensorView>> results;
    for (shared_ptr<Node> out : f->get_results())
    {
        auto result = backend->make_primary_tensor_view(out->get_element_type(), out->get_shape());
        results.push_back(result);
92 93 94 95
    }

    stopwatch t1;
    t1.start();
96
    for (size_t i = 0; i < static_cast<size_t>(iterations); i++)
97
    {
98
        cf->tensor_call(args, results);
99 100 101
    }
    t1.stop();
    float time = t1.get_milliseconds();
102
    cout << time / iterations << "ms per iteration" << endl;
103

104 105 106 107 108 109 110 111
    vector<runtime::PerformanceCounter> perf_data = cf->get_performance_data();
    sort(perf_data.begin(),
         perf_data.end(),
         [](const runtime::PerformanceCounter& p1, const runtime::PerformanceCounter& p2) {
             return p1.total_microseconds() > p2.total_microseconds();
         });
    multimap<size_t, string> timing = agregate_timing(perf_data);
    for (auto it = timing.rbegin(); it != timing.rend(); it++)
112
    {
113 114
        cout.imbue(locale(""));
        cout << setw(15) << left << it->second << " " << setw(10) << right << it->first << "us\n";
115 116
    }
}
117

118 119 120
TEST(benchmark, mxnet_mnist_mlp_forward)
{
    const string json_path = file_util::path_join(SERIALIZED_ZOO, "mxnet/mnist_mlp_forward.json");
121
    run_benchmark(json_path, "CPU", 1000);
122 123 124 125 126
}

TEST(benchmark, mxnet_10_bucket_lstm)
{
    const string json_path = file_util::path_join(SERIALIZED_ZOO, "mxnet/10_bucket_LSTM.json");
127 128 129
    run_benchmark(json_path, "CPU", 10);
}

130 131 132
TEST(benchmark, mxnet_lstm_backward)
{
    const string json_path = file_util::path_join(SERIALIZED_ZOO, "mxnet/LSTM_backward.json");
133 134 135
    run_benchmark(json_path, "CPU", 10);
}

136
TEST(benchmark, mxnet_lstm_forward)
137
{
138 139
    const string json_path = file_util::path_join(SERIALIZED_ZOO, "mxnet/LSTM_forward.json");
    run_benchmark(json_path, "CPU", 10);
140 141
}

142
TEST(benchmark, mxnet_seq2seq_forward)
143
{
144
    const string json_path = file_util::path_join(SERIALIZED_ZOO, "mxnet/Seq2Seq_forward.json");
145 146 147
    run_benchmark(json_path, "CPU", 10);
}

148
TEST(benchmark, mxnet_seq2seq_backward)
149
{
150 151
    const string json_path = file_util::path_join(SERIALIZED_ZOO, "mxnet/Seq2Seq_backward.json");
    run_benchmark(json_path, "CPU", 10);
152 153
}

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
//
// Benchmarks a graph that concatenates six 32x1x200 arrays along the middle axis.
//
TEST(benchmark, concat_32x1x200_axis1_6)
{
    const size_t n_arrays = 6;
    Shape shape_of_each_array = Shape{32, 1, 200};
    size_t concatenation_axis = 1;

    Shape result_shape;
    result_shape = shape_of_each_array;
    result_shape[concatenation_axis] *= n_arrays;

    size_t elements_per_array = 1;
    for (size_t d : shape_of_each_array)
    {
        elements_per_array *= d;
    }

    vector<vector<float>> data_arrays(n_arrays);
    for (size_t i = 0; i < n_arrays; i++)
    {
        data_arrays[i] = vector<float>(elements_per_array);
        for (size_t j = 0; j < elements_per_array; j++)
        {
            data_arrays[i][j] = float(j + 1);
        }
    }

    bool using_ref_kernels = (std::getenv("NGRAPH_CPU_USE_REF_KERNELS") != nullptr);

185
    vector<std::string> backend_names{"INTERPRETER", "CPU"};
186 187 188 189 190 191 192 193 194 195
    vector<int> n_runs{200, 200, using_ref_kernels ? 200 : 200000}; // one for each backend
    vector<std::function<void()>> test_callbacks;                   // one for each backend
    vector<std::shared_ptr<runtime::TensorView>> result_tvs;        // one for each backend

    for (std::string backend_name : backend_names)
    {
        vector<std::shared_ptr<op::Parameter>> params(n_arrays);
        vector<std::shared_ptr<Node>> params_as_nodes(n_arrays);
        for (size_t i = 0; i < n_arrays; i++)
        {
196
            auto param = make_shared<op::Parameter>(element::f32, shape_of_each_array);
197 198 199 200 201 202 203 204 205 206 207 208
            params[i] = param;
            params_as_nodes[i] = param;
        }

        auto concat = make_shared<op::Concat>(params_as_nodes, concatenation_axis);
        auto f = make_shared<Function>(concat, params);

        auto manager = runtime::Manager::get(backend_name);
        auto external = manager->compile(f);
        auto backend = manager->allocate_backend();
        auto cf = backend->make_call_frame(external);

209
        vector<shared_ptr<runtime::TensorView>> input_vals;
210 211 212

        for (size_t i = 0; i < n_arrays; i++)
        {
213
            auto tv = backend->make_primary_tensor_view(element::f32, shape_of_each_array);
214 215 216 217
            copy_data(tv, data_arrays[i]);
            input_vals.push_back(tv);
        }

218
        auto result_tv = backend->make_primary_tensor_view(element::f32, result_shape);
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
        result_tvs.push_back(result_tv);

        std::function<void()> cb = [input_vals, result_tv, cf]() {
            cf->call(input_vals, {result_tv});
        };

        test_callbacks.push_back(cb);
    }

    for (size_t i = 0; i < backend_names.size(); i++)
    {
        std::cout << backend_names[i] << ": " << n_runs[i] << " tests in " << std::flush;

        stopwatch sw;
        std::function<void()> cb = test_callbacks[i];

        sw.start();
        for (int j = 0; j < n_runs[i]; j++)
        {
            cb();
        }
        sw.stop();

        std::cout << sw.get_milliseconds() << "ms (" << (sw.get_microseconds() / n_runs[i])
                  << " us/test)" << std::endl;
    }

    for (size_t i = 1; i < backend_names.size(); i++)
    {
        std::cout << "Verifying " << backend_names[i] << " result against " << backend_names[0]
                  << "..." << std::flush;

251
        if (read_vector<float>(result_tvs[i]) == read_vector<float>(result_tvs[0]))
252 253 254 255 256 257 258 259 260 261
        {
            std::cout << " OK" << std::endl;
        }
        else
        {
            std::cout << " FAILED" << std::endl;
            ADD_FAILURE();
        }
    }
}