states.h 23.4 KB
Newer Older
1 2
#pragma once

3 4 5 6
#include <algorithm>
#include <chrono>
#include <ctime>

7
#include <any>
M
Megvii Engine Team 已提交
8
#include <set>
9
#include <sstream>
M
Megvii Engine Team 已提交
10
#include <typeindex>
11 12

#include "nlohmann/json.hpp"
13 14 15

#include "megbrain/tensor.h"

16 17
#include "./events.h"

18 19
namespace mgb::imperative::profiler {

20
using StackManager = interpreter::intl::StackManager;
21 22

struct ProfileTensorState {
23 24
    uint64_t id = 0;
    std::optional<uint64_t> source;
25 26 27
    TensorLayout layout;
    CompNode device;
    std::string name;
28 29
    profiler::HostTime produced = profiler::HostTime::min();
    profiler::Duration living_time = profiler::Duration::zero();
30 31 32 33 34 35 36 37

    size_t size_in_bytes() const {
        if (!layout.dtype.valid()) {
            return 0;
        }
        return layout.dtype.size(layout.total_nr_elems());
    }

38 39 40
    std::string info(HostTime current_time) {
        std::string shape = layout.TensorShape::to_string();
        std::string dtype = layout.dtype.name();
M
Megvii Engine Team 已提交
41 42 43
        return ssprintf(
                "%s(%s:%s:%s)", name.c_str(), shape.c_str(), dtype.c_str(),
                device.to_string().c_str());
44 45 46 47 48 49 50 51 52 53 54
    }

    nlohmann::json detail(HostTime current_time) {
        nlohmann::json args;
        args["id"] = id;
        args["name"] = name;
        args["shape"] = layout.TensorShape::to_string();
        args["dtype"] = layout.dtype.name();
        args["nr_elements"] = layout.total_nr_elems();
        args["device"] = device.to_string();
        if (produced != produced.min()) {
M
Megvii Engine Team 已提交
55 56 57 58
            double ms_count = std::chrono::duration_cast<
                                      std::chrono::duration<double, std::micro>>(
                                      current_time - produced + living_time)
                                      .count();
59 60 61 62
            args["living_time"] = ssprintf("%lf ms", ms_count);
        }
        return args;
    }
63 64 65
};

struct ProfileOperatorState {
66
    uint64_t id = 0;
67
    std::string name;
68
    OpParams params;
69 70 71
    SmallVector<uint64_t> inputs;
    SmallVector<uint64_t> outputs;
    CompNode device;
72
    Trace trace;
73

74 75 76 77 78 79 80
    struct Execution {
        std::string reason;
        profiler::HostTime begin;
        profiler::HostTime end;
    };

    SmallVector<Execution> executions;
81

82 83
    nlohmann::json detail() {
        nlohmann::json args;
M
Megvii Engine Team 已提交
84
        for (auto&& [name, value] : params) {
85 86 87 88 89 90 91
            args[name] = value;
        }
        args["__id__"] = id;
        args["__name__"] = name;
        args["__device__"] = device.to_string();
        return args;
    }
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
};

template <typename TProp>
struct ProfileTensorPropPair {
    uint64_t id;
    TProp value;

    bool operator<(const ProfileTensorPropPair& lhs) const {
        return value == lhs.value ? id < lhs.id : value < lhs.value;
    }

    bool operator==(const ProfileTensorPropPair& lhs) const {
        return id == lhs.id && value == lhs.value;
    }

    bool operator>(const ProfileTensorPropPair& lhs) const {
        return value == lhs.value ? id > lhs.id : value > lhs.value;
    }
};

using ProfileTensorSizePair = ProfileTensorPropPair<size_t>;
using ProfileTensorProducedPair = ProfileTensorPropPair<uint64_t>;

struct ProfileState {
    std::unordered_map<uint64_t, ProfileTensorState> tensors;
    std::unordered_map<uint64_t, ProfileOperatorState> operators;
    std::unordered_map<std::string, uint64_t> tensor_name_counter;
    std::set<ProfileTensorSizePair> tensors_by_size;
    std::set<ProfileTensorSizePair> tensors_by_produced;

    std::vector<uint64_t> top_k_tensor_in_device(CompNode device, size_t k) {
        std::vector<uint64_t> results;
M
Megvii Engine Team 已提交
124 125
        for (auto iter = tensors_by_size.rbegin(); iter != tensors_by_size.rend();
             ++iter) {
126 127 128 129 130 131 132 133 134 135
            if (!k) {
                break;
            }
            if (tensors[iter->id].device == device) {
                results.push_back(iter->id);
                --k;
            }
        }
        return results;
    }
136
};
137

M
Megvii Engine Team 已提交
138 139
template <typename T, typename = void>
struct is_op_event : std::false_type {};
140

M
Megvii Engine Team 已提交
141 142
template <typename T>
struct is_op_event<T, decltype(std::declval<T>().op_id, void())> : std::true_type {};
143

M
Megvii Engine Team 已提交
144 145
template <typename T, typename = void>
struct is_tensor_event : std::false_type {};
146

M
Megvii Engine Team 已提交
147 148 149 150 151 152 153
template <typename T>
struct is_tensor_event<T, decltype(std::declval<T>().tensor_id, void())>
        : std::true_type {};
template <typename T, typename = void>
struct is_trace_event : std::false_type {};
template <typename T>
struct is_trace_event<T, decltype(std::declval<T>().trace, void())> : std::true_type {};
154 155 156 157

template <typename... TItems>
class AnyToVariantConverter {
public:
158
    using any_t = AnyPtr;
159
    using variant_t = std::variant<TItems...>;
M
Megvii Engine Team 已提交
160

161
private:
162
    std::unordered_map<std::type_index, std::function<variant_t(const any_t&)>> m_table;
163 164 165

    template <typename TItem>
    void register_converter() {
166
        m_table[typeid(TItem)] = [](const any_t& input) {
167
            return variant_t(input.cast<TItem>());
168 169
        };
    }
M
Megvii Engine Team 已提交
170

171
public:
M
Megvii Engine Team 已提交
172
    AnyToVariantConverter() { (register_converter<TItems>(), ...); }
173
    variant_t operator()(const any_t& input) {
174 175 176 177 178 179 180 181 182 183 184 185 186
        return m_table[input.type()](std::move(input));
    }
};

template <typename TSelf>
class EventVisitor {
private:
    std::unordered_map<size_t, ProfileOperatorState> m_operators;
    std::unordered_map<size_t, ProfileTensorState> m_tensors;
    std::unordered_map<size_t, std::vector<Profiler::Record>> m_duration_stack;
    HostTime m_start_time;
    CompNode::UnorderedMap<size_t> m_device_tid_table;
    std::unordered_map<std::thread::id, size_t> m_host_tid_table;
187
    std::unordered_map<cupti::stream_t, size_t> m_cupti_tid_table;
M
Megvii Engine Team 已提交
188 189
    CompNode::UnorderedMap<std::map<profiler::HostTime, profiler::RealDuration>>
            m_device_timeline;
190 191
    std::unordered_map<std::thread::id, std::vector<Trace>> m_trace_stack;
    std::unordered_map<std::string, int64_t> m_counter_table;
192 193
    std::optional<std::pair<profiler::HostTime, cupti::time_point>> m_cupti_timestamp =
            {};
194 195 196 197 198 199 200 201 202 203 204 205
    // Record the start and end time of all kernels
    std::vector<std::vector<profiler::HostTime>> m_kernel_start_finish_time;
    // The sum of all kernel execution times
    profiler::Duration m_gpu_usage_time = std::chrono::microseconds(0);
    // The sum of all kernel execution times, including the gap time between kernels
    // within a step
    profiler::Duration m_gpu_usage_time_with_gap = std::chrono::microseconds(0);
    // Record the end time of each step
    std::vector<profiler::HostTime> m_step_finish_time;
    // Record the start time of the first kernel and the end time of the last kernel in
    // each step
    std::vector<std::vector<profiler::HostTime>> m_step_first_last_kernel;
M
Megvii Engine Team 已提交
206

207 208 209 210
protected:
    Profiler::Record* current;
    ProfileOperatorState* current_op;
    ProfileTensorState* current_tensor;
M
Megvii Engine Team 已提交
211

212
protected:
213 214 215 216 217
    size_t next_tid() {
        return m_host_tid_table.size() + m_device_tid_table.size() +
               m_cupti_tid_table.size();
    }

218 219 220 221 222 223 224 225 226 227 228 229
    profiler::Duration since_start(profiler::HostTime time) {
        return time - m_start_time;
    }

    profiler::HostTime to_device_time(profiler::HostTime time, CompNode device) {
        auto& device_timeline = m_device_timeline[device];
        auto upper = device_timeline.lower_bound(time);
        if (upper == device_timeline.end()) {
            if (upper == device_timeline.begin()) {
                return time;
            } else {
                --upper;
M
Megvii Engine Team 已提交
230 231
                return time +
                       std::chrono::duration_cast<profiler::Duration>(upper->second);
232 233 234 235 236
            }
        } else if (upper->first == time) {
            return time + std::chrono::duration_cast<profiler::Duration>(upper->second);
        } else if (upper == device_timeline.begin()) {
            return time + std::chrono::duration_cast<profiler::Duration>(upper->second);
237
        }
238
        auto lower = upper;
M
Megvii Engine Team 已提交
239 240 241 242
        --lower;
        double ratio =
                ((double)(time - lower->first).count() /
                 (double)(upper->first - lower->first).count());
243
        mgb_assert(ratio > 0 && ratio < 1, "invalid ratio");
M
Megvii Engine Team 已提交
244 245 246
        mgb_assert(
                lower->first + lower->second <= upper->first + upper->second,
                "device time corr");
247 248
        auto shift = lower->second + ratio * (upper->second - lower->second);
        auto result = time + std::chrono::duration_cast<profiler::Duration>(shift);
249 250
        return result;
    }
251

M
Megvii Engine Team 已提交
252
    size_t to_tid(std::thread::id host_tid) { return m_host_tid_table.at(host_tid); }
253

M
Megvii Engine Team 已提交
254
    size_t to_tid(CompNode device) { return m_device_tid_table.at(device); }
255

256 257 258 259
    size_t to_tid(cupti::stream_t cupti_stream) {
        return m_cupti_tid_table.at(cupti_stream);
    }

260 261
    SmallVector<std::thread::id> host_threads() {
        SmallVector<std::thread::id> host_threads;
M
Megvii Engine Team 已提交
262
        for (auto&& [host, _] : m_host_tid_table) {
263 264 265 266 267 268 269
            host_threads.push_back(host);
        }
        return host_threads;
    }

    SmallVector<CompNode> devices() {
        SmallVector<CompNode> devices;
M
Megvii Engine Team 已提交
270
        for (auto&& [device, _] : m_device_tid_table) {
271 272 273 274 275
            devices.push_back(device);
        }
        return devices;
    }

276 277 278 279 280 281 282 283
    void inc_counter(const char* key, int64_t delta) {
        if (!m_counter_table.count(key)) {
            m_counter_table[key] = 0;
        }
        auto& value = m_counter_table[key];
        static_cast<TSelf&>(*this).notify_counter(key, value, value + delta);
        value += delta;
    }
M
Megvii Engine Team 已提交
284

285 286 287 288 289 290 291
    profiler::HostTime time_from_cupti(cupti::time_point timestamp) {
        mgb_assert(m_cupti_timestamp.has_value());
        return m_cupti_timestamp->first +
               std::chrono::duration_cast<profiler::HostTime::duration>(
                       timestamp - m_cupti_timestamp->second);
    }

292
public:
293
    void process_events(Profiler::bundle_t& bundle) {
294 295 296
        m_start_time = bundle.start_at;

        auto& self = static_cast<TSelf&>(*this);
M
Megvii Engine Team 已提交
297 298 299 300 301 302 303 304 305 306
        AnyToVariantConverter<
                OpDispatchEvent, OpExecuteEvent, OpExecuteFinishEvent,
                KernelLaunchEvent, KernelLaunchFinishEvent, OpInputEvent,
                OpInputFinishEvent, OpOutputEvent, OpOutputFinishEvent,
                TensorDeclareEvent, TensorProduceEvent, TensorUsageEvent,
                TensorReleaseEvent, TensorEraseEvent, TensorGetPropEvent,
                TensorNotifyPropEvent, TensorWaitPropEvent, TensorWaitPropFinishEvent,
                SampleDeviceEvent, SampleDeviceFinishEvent, WorkerExceptionEvent,
                ShapeInferEvent, SyncEvent, SyncFinishEvent, StartProfileEvent,
                StartProfileFinishEvent, StopProfileEvent, StopProfileFinishEvent,
307 308 309
                StopStepEvent, TensorCommandEvent, TensorCommandFinishEvent,
                AutoEvictEvent, AutoEvictFinishEvent, CustomEvent, CustomFinishEvent,
                RecordDeviceEvent, ScopeEvent, ScopeFinishEvent, HostToDeviceEvent,
310 311 312 313 314
                HostToDeviceFinishEvent, CUPTITimestampEvent, CUPTIKernelLaunchEvent,
                CUPTIKernelLaunchFinishEvent, CUPTIKernelExecuteEvent,
                CUPTIMemcpyLaunchEvent, CUPTIMemcpyLaunchFinishEvent, CUPTIMemcpyEvent,
                CUPTIRuntimeEvent, CUPTIRuntimeFinishEvent, CUPTIDriverEvent,
                CUPTIDriverFinishEvent, CUPTIMemsetEvent>
M
Megvii Engine Team 已提交
315
                converter;
316 317

        auto for_each_entry = [&](auto&& handler) {
M
Megvii Engine Team 已提交
318
            for (auto& entry : bundle.entries) {
319 320 321 322 323 324 325 326 327 328 329 330
                current = &entry;
                std::visit(handler, converter(entry.data));
            }
            current = nullptr;
        };

        // build device timeline
        struct DeviceStartPair {
            profiler::HostTime host;
            std::shared_ptr<CompNode::Event> device;
        };
        CompNode::UnorderedMap<DeviceStartPair> device_start_table;
331
        std::unordered_map<cupti::stream_t, CompNode> cupti_stream_table;
332

333
        // record device time
M
Megvii Engine Team 已提交
334
        for_each_entry([&](auto&& event) {
335 336 337
            using T = std::decay_t<decltype(event)>;
            if constexpr (std::is_same_v<T, RecordDeviceEvent>) {
                using namespace std::chrono_literals;
M
Megvii Engine Team 已提交
338 339
                DeviceStartPair& device_start =
                        device_start_table[event.event->comp_node()];
340
                if (!device_start.device) {
M
Megvii Engine Team 已提交
341
                    device_start = {current->time, event.event};
342 343
                }
                event.event->host_wait();
M
Megvii Engine Team 已提交
344 345 346 347 348 349 350
                auto device_time =
                        (device_start.host - current->time) +
                        std::chrono::duration_cast<profiler::RealDuration>(
                                device_start.device->elapsed_time_until(*event.event) *
                                1s);
                m_device_timeline[event.event->comp_node()][current->time] =
                        device_time;
351 352 353
            }
        });

354 355 356 357 358 359 360 361 362
        // record step end time
        for_each_entry([&](auto&& event) {
            using T = std::decay_t<decltype(event)>;
            if constexpr (std::is_same_v<T, StopStepEvent>) {
                auto step_time = current->time;
                m_step_finish_time.push_back(to_device_time(step_time, event.device));
            }
        });

363
        // register host threads
M
Megvii Engine Team 已提交
364
        for_each_entry([&](auto&& event) {
365
            if (!m_host_tid_table.count(current->tid)) {
366
                m_host_tid_table[current->tid] = next_tid();
367 368 369
            }
        });

M
Megvii Engine Team 已提交
370
        for_each_entry([&](auto&& event) {
371 372 373 374 375 376 377 378 379 380
            using T = std::decay_t<decltype(event)>;
            if constexpr (std::is_same_v<T, OpDispatchEvent>) {
                auto& op = m_operators[event.op_id];
                mgb_assert(op.id == 0, "duplicate operator id");
                op.id = event.op_id;
                op.name = event.op_name;
                op.params = event.op_params();
                op.inputs = event.inputs;
                op.outputs = event.outputs;
                op.trace = event.trace;
M
Megvii Engine Team 已提交
381
                for (auto&& output : event.outputs) {
382
                    m_tensors[output].source = op.id;
383 384 385 386 387 388 389
                }
            } else if constexpr (std::is_same_v<T, TensorDeclareEvent>) {
                auto& tensor = m_tensors[event.tensor_id];
                mgb_assert(tensor.id == 0, "duplicated tensor id");
                tensor.id = event.tensor_id;
                tensor.name = event.name;
            } else if constexpr (std::is_same_v<T, TensorProduceEvent>) {
390
                auto& tensor = m_tensors[event.tensor_id];
391
                if (!m_device_tid_table.count(event.device)) {
392
                    m_device_tid_table[event.device] = next_tid();
393 394
                }
                tensor.device = event.device;
395
                tensor.layout = event.layout;
396 397 398
            }
        });

399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
        for_each_entry([&](auto&& event) {
            using T = std::decay_t<decltype(event)>;
            if constexpr (std::is_same_v<T, CUPTIIdentifyStreamEvent>) {
                if (!m_cupti_tid_table.count(event.stream)) {
                    m_cupti_tid_table[event.stream] =
                            m_device_tid_table.at(event.device);
                }
            }
        });

        // record cupti streams
        for_each_entry([&](auto&& event) {
            using T = std::decay_t<decltype(event)>;
            if constexpr (
                    std::is_same_v<T, CUPTIKernelExecuteEvent> ||
                    std::is_same_v<T, CUPTIMemcpyEvent> ||
                    std::is_same_v<T, CUPTIMemsetEvent>) {
                if (!m_cupti_tid_table.count(event.stream)) {
                    m_cupti_tid_table[event.stream] = next_tid();
                }
            } else if constexpr (std::is_same_v<T, CUPTITimestampEvent>) {
                mgb_assert(!m_cupti_timestamp.has_value());
                m_cupti_timestamp.emplace(current->time, event.timestamp);
            }
        });

425 426
        // replay execution
        using namespace std::placeholders;
M
Megvii Engine Team 已提交
427
        for_each_entry([&](auto&& event) {
428 429 430
            using T = std::decay_t<decltype(event)>;
            // update current_op/tensor
            if constexpr (is_op_event<T>::value) {
431 432 433 434 435
                current_op = &m_operators[event.op_id];
                if (current_op->id == 0) {
                    current_op->id = event.op_id;
                    current_op->name = "UnknownOperator";
                }
436
            } else if constexpr (is_tensor_event<T>::value) {
437 438 439 440 441
                current_tensor = &m_tensors[event.tensor_id];
                if (current_tensor->id == 0) {
                    current_tensor->id = event.tensor_id;
                    current_tensor->name = "UnknownTensor";
                }
442 443
            }
            if constexpr (std::is_same_v<T, OpExecuteEvent>) {
444 445 446
                current_op->executions.emplace_back();
                current_op->executions.back().reason = event.reason;
                current_op->executions.back().begin = current->time;
447
            } else if constexpr (std::is_same_v<T, OpExecuteFinishEvent>) {
448
                current_op->executions.back().end = current->time;
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
            }
            // update counters
            if constexpr (std::is_same_v<T, OpDispatchEvent>) {
                inc_counter("nr_op_pending", 1);
            } else if constexpr (std::is_same_v<T, OpExecuteEvent>) {
                inc_counter("nr_op_pending", -1);
            } else if constexpr (std::is_same_v<T, TensorProduceEvent>) {
                inc_counter("nr_alive_tensor", 1);
            } else if constexpr (std::is_same_v<T, TensorReleaseEvent>) {
                inc_counter("nr_alive_tensor", -1);
            } else if constexpr (std::is_same_v<T, TensorEraseEvent>) {
                if (event.use_count == 0) {
                    inc_counter("nr_redunant_tensor", 1);
                }
            } else if constexpr (std::is_same_v<T, ShapeInferEvent>) {
                if (!event.success) {
                    inc_counter("nr_shape_infer_failure", 1);
                }
            } else if constexpr (std::is_same_v<T, WorkerExceptionEvent>) {
                inc_counter("nr_exception", 1);
469 470
            } else if constexpr (std::is_same_v<T, KernelLaunchFinishEvent>) {
                auto& execution = current_op->executions.back();
471 472 473 474 475 476 477 478 479 480
                auto overhead = to_device_time(current->time, event.device) -
                                to_device_time(execution.begin, event.device);

                std::vector<profiler::HostTime> current_kernel_start_finish;
                current_kernel_start_finish.emplace_back(
                        to_device_time(execution.begin, event.device));
                current_kernel_start_finish.emplace_back(
                        to_device_time(current->time, event.device));
                m_kernel_start_finish_time.emplace_back(current_kernel_start_finish);

481
                if (execution.reason == "dtr") {
M
Megvii Engine Team 已提交
482 483 484 485 486
                    inc_counter(
                            "dtr_overhead_us",
                            std::chrono::duration_cast<std::chrono::microseconds>(
                                    overhead)
                                    .count());
487
                }
488 489 490 491 492 493 494 495 496 497 498
            }
            // visit_event_impl
            self.visit_event(event);
            // reset current_op/tensor
            if constexpr (is_op_event<T>::value) {
                current_op = nullptr;
            } else if constexpr (is_tensor_event<T>::value) {
                current_tensor = nullptr;
            }
        });
    }
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601

    profiler::Duration last_kernel_finish() {
        if (m_kernel_start_finish_time.size() == 0) {
            return profiler::Duration::zero();
        }
        return m_kernel_start_finish_time.back()[1] - m_start_time;
    }

    // get GPU busy time (union of calculation time and communication time)
    profiler::Duration gpu_usage_time() {
        if (m_kernel_start_finish_time.size() == 0) {
            return profiler::Duration::zero();
        }

        std::sort(
                m_kernel_start_finish_time.begin(), m_kernel_start_finish_time.end(),
                [&](std::vector<profiler::HostTime> kernel1,
                    std::vector<profiler::HostTime> kernel2) {
                    if (kernel1[0] != kernel2[0]) {
                        return kernel1[0] < kernel2[0];
                    }
                    return kernel1[1] < kernel2[1];
                });

        HostTime current_start = profiler::HostTime::min();
        HostTime current_end = profiler::HostTime::min();
        for (size_t i = 0; i < m_kernel_start_finish_time.size(); ++i) {
            if (current_start == profiler::HostTime::min()) {
                current_start = m_kernel_start_finish_time[i][0];
                current_end = m_kernel_start_finish_time[i][1];
            } else if (current_end < m_kernel_start_finish_time[i][0]) {
                m_gpu_usage_time += profiler::Duration(current_end - current_start);
                current_start = m_kernel_start_finish_time[i][0];
                current_end = m_kernel_start_finish_time[i][1];
            } else if (current_end > m_kernel_start_finish_time[i][0]) {
                current_end = max(current_end, m_kernel_start_finish_time[i][1]);
            }
        }
        m_gpu_usage_time += profiler::Duration(current_end - current_start);

        return m_gpu_usage_time;
    }

    // compared to gpu_usage_time, this method adds gap time between kernels in the same
    // step
    profiler::Duration gpu_usage_time_with_gap() {
        if (m_step_finish_time.empty()) {
            return profiler::Duration::zero();
        }

        std::sort(
                m_step_finish_time.begin(), m_step_finish_time.end(),
                [&](HostTime time1, HostTime time2) { return time1 < time2; });

        std::sort(
                m_kernel_start_finish_time.begin(), m_kernel_start_finish_time.end(),
                [&](std::vector<profiler::HostTime> kernel1,
                    std::vector<profiler::HostTime> kernel2) {
                    if (kernel1[0] != kernel2[0]) {
                        return kernel1[0] < kernel2[0];
                    }
                    return kernel1[1] < kernel2[1];
                });

        int cur_step = 0;
        auto kernel_num = m_kernel_start_finish_time.size();
        for (size_t i = 0; i < kernel_num; ++i) {
            // Record the start time of the first kernel and the end time of the last
            // kernel of the current step
            std::vector<profiler::HostTime> step_begin_end_time;
            step_begin_end_time.emplace_back(m_kernel_start_finish_time[i][0]);
            size_t j = i;
            while (j < kernel_num && m_kernel_start_finish_time[j][0] <
                                             m_step_finish_time[cur_step + 1]) {
                ++j;
            }
            step_begin_end_time.emplace_back(m_kernel_start_finish_time[j - 1][1]);
            mgb_assert(
                    step_begin_end_time.size() == 2,
                    "step_begin_end_time.size() should be exactly 2!");
            m_step_first_last_kernel.emplace_back(step_begin_end_time);
            i = j - 1;
            ++cur_step;
        }

        for (size_t i = 0; i < m_step_first_last_kernel.size(); ++i) {
            m_gpu_usage_time_with_gap += profiler::Duration(
                    m_step_first_last_kernel[i][1] - m_step_first_last_kernel[i][0]);
        }

        return m_gpu_usage_time_with_gap;
    }

    // from the start time of the first kernel of the first step to the end time of the
    // last kernel of the last step
    std::chrono::microseconds get_total_train_time() {
        if (m_kernel_start_finish_time.size() == 0) {
            return std::chrono::microseconds(1);
        }
        return std::chrono::duration_cast<std::chrono::microseconds>(
                m_kernel_start_finish_time.back()[1] -
                m_kernel_start_finish_time.front()[0]);
    }
602 603
};

M
Megvii Engine Team 已提交
604
}  // namespace mgb::imperative::profiler