comp_node.cpp 39.1 KB
Newer Older
1 2 3 4
/**
 * \file src/core/impl/comp_node/cpu/comp_node.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
6 7 8 9 10 11 12 13
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

#include "./comp_node.h"

14
#include "megbrain/common.h"
15 16 17 18 19
#include "megbrain/comp_node_env.h"
#include "megbrain/system.h"
#include "megbrain/utils/arith_helper.h"
#include "megbrain/utils/thread.h"
#include "megbrain/utils/thread_pool.h"
20
#include "megbrain/utils/timer.h"
21

22
#include <atomic>
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
#include <condition_variable>
#include <cstdint>
#include <cstring>

#include <stdlib.h>
#ifndef __APPLE__
#include <malloc.h>
#endif

using namespace mgb;

namespace {
bool enable_affinity = false;
using Task = CompNodeEnv::CpuEnv::Task;
using MultiThreadingTask = megcore::CPUDispatcher::MultiThreadingTask;

struct TaskElem {
    //! the task to be execute
    MultiThreadingTask task;
    //! number of the parallelism
    size_t nr_parallelism;
};
}  // anonymous namespace

void CpuCompNode::CpuDispatchableBase::add_callback(Task&& task) {
    dispatch(std::move(task));
}

class CpuCompNode::WorkerQueue final
        : public AsyncQueueSC<TaskElem, WorkerQueue> {
    const Locator m_locator;
    ThreadPool* m_thread_pool = nullptr;

    void on_async_queue_worker_thread_start() override {
        mgb_assert(m_locator.device >= 0);
        if (enable_affinity) {
59
#if !defined(ANDROID) && !defined(__ANDROID__)
60
            sys::set_cpu_affinity({m_locator.device});
61
#endif
62 63 64 65 66
        }
        sys::set_thread_name(m_locator.to_string());
    }

    void on_sync_all_task_finish() override {
67
        if (m_thread_pool) {
68
            m_thread_pool->deactive();
69
        }
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
    }

public:
    class DispatcherImpl;

    explicit WorkerQueue(Locator locator) : m_locator(locator) {}

    void attach_thread_pool(ThreadPool* thread_pool) {
        m_thread_pool = thread_pool;
    }

    void process_one_task(const TaskElem& task_elem) {
        if (m_thread_pool) {
            m_thread_pool->add_task(task_elem);
        } else {
            for (size_t i = 0; i < task_elem.nr_parallelism; i++) {
                task_elem.task(i, 0);
            }
        }
    }

    int nr_threads() {
        return m_thread_pool ? m_thread_pool->nr_threads() : 1_z;
    }

    ThreadPool* get_thread_pool() { return m_thread_pool; }
};

class CpuCompNode::SeqRecorderImpl final : public CompNodeSeqRecorder {
    using CpuEnv = CompNodeEnv::CpuEnv;
    bool m_fake_exec = false, m_synchronized = false, m_stopped = false,
         m_first_replay = true;
    SeqRecorderImpl** const m_self_pointer;

    std::vector<TaskElem> m_tasks;
    ThreadPool* m_thread_pool = nullptr;
106 107 108 109 110
    const CompNode m_record_compnode;
    /*!
     * \brief use to check the all ther recording tasks are its self CompNode
     * related task, void hook other CompNode related task to the recorder.
     */
111 112 113 114 115 116 117 118 119
    void check_the_same_comp_node(const CompNode& comp_node) const {
        if (mgb_unlikely(comp_node.valid())) {
            mgb_assert(m_record_compnode == comp_node,
                       "CompNode %s can't hook in CompNode %s when recording\n",
                       comp_node.locator().to_string().c_str(),
                       m_record_compnode.locator().to_string().c_str());
        }
    }

120
public:
121 122
    SeqRecorderImpl(SeqRecorderImpl** self_pointer, ThreadPool* thread_pool,
                    const CompNode& comp_node)
123
            : m_self_pointer{self_pointer},
124 125
              m_thread_pool{thread_pool},
              m_record_compnode{comp_node} {
126 127 128 129 130 131 132 133 134 135
        mgb_assert(!*m_self_pointer);
        *m_self_pointer = this;
    }

    ~SeqRecorderImpl() {
        if (*m_self_pointer) {
            stop();
        }
    }

136
    void enter_fake_exec(const CompNode& comp_node) override {
137
        check_the_same_comp_node(comp_node);
138 139 140 141
        mgb_assert(!m_stopped && !m_fake_exec);
        m_fake_exec = true;
    }

142
    void exit_fake_exec(const CompNode& comp_node) override {
143
        check_the_same_comp_node(comp_node);
144 145 146 147 148 149
        mgb_assert(!m_stopped && m_fake_exec);
        mgb_assert(m_tasks.empty());
        m_fake_exec = false;
        m_synchronized = false;
    }

150 151
    void stop(const CompNode& comp_node = {}) override {
        check_the_same_comp_node(comp_node);
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        mgb_assert(*m_self_pointer == this);
        mgb_assert(!m_fake_exec);
        *m_self_pointer = nullptr;
        m_stopped = true;
    }

    void replay() override {
        mgb_assert(m_stopped, "not stopped yet");
        if (m_first_replay) {
            // check that dispatch is not called from tasks
            mgb_assert(!*m_self_pointer,
                       "no other seq recorder should be created before first "
                       "replay");
            *m_self_pointer = this;
        }
        MGB_TRY {
            if (m_thread_pool) {
                m_thread_pool->active();
                for (auto&& i : m_tasks) {
                    m_thread_pool->add_task(i);
                }
                m_thread_pool->deactive();
174
            } else {
175
                for (auto&& task : m_tasks) {
176
                    for (size_t i = 0; i < task.nr_parallelism; i++) {
177 178 179 180 181 182 183 184 185 186 187 188 189
                        task.task(i, 0);
                    }
                }
            }
        }
        MGB_FINALLY({
            if (m_first_replay) {
                stop();
                m_first_replay = false;
            }
        });
    }

190 191
    void on_alloc(const CompNode& comp_node) {
        check_the_same_comp_node(comp_node);
192 193 194 195
        mgb_assert(m_fake_exec,
                   "alloc is disallowed during comp node seq recording");
    }

196 197
    void on_free(const CompNode& comp_node) {
        check_the_same_comp_node(comp_node);
198 199 200 201
        mgb_assert(m_fake_exec,
                   "free is disallowed during comp node seq recording");
    }

202 203 204 205
    void on_sync(const CompNode& comp_node) {
        check_the_same_comp_node(comp_node);
        m_synchronized = true;
    }
206

207
    void dispatch(Task&& task, const CompNode& comp_node) {
208 209 210
        mgb_assert(!m_synchronized,
                   "no more tasks should be dispatched after synchronization");
        auto kern = [task](size_t, size_t) { task(); };
211 212
        dispatch_allow_after_sync({std::move(kern), static_cast<size_t>(1_z)},
                                  comp_node);
213
    }
214 215
    void dispatch_allow_after_sync(Task&& task, const CompNode& comp_node) {
        check_the_same_comp_node(comp_node);
216 217 218 219 220 221 222
        mgb_assert(!m_stopped,
                   "dispatch should not be called after recording is stopped");
        if (!m_fake_exec) {
            auto kern = [task](size_t, size_t) { task(); };
            m_tasks.push_back({std::move(kern), static_cast<size_t>(1_z)});
        }
    }
223
    void dispatch(TaskElem&& task_elem, const CompNode& comp_node) {
224 225
        mgb_assert(!m_synchronized,
                   "no more tasks should be dispatched after synchronization");
226
        dispatch_allow_after_sync(std::move(task_elem), comp_node);
227
    }
228 229 230
    void dispatch_allow_after_sync(TaskElem&& task_elem,
                                   const CompNode& comp_node) {
        check_the_same_comp_node(comp_node);
231 232 233 234 235 236
        mgb_assert(!m_stopped,
                   "dispatch should not be called after recording is stopped");
        if (!m_fake_exec) {
            m_tasks.push_back(task_elem);
        }
    }
237 238
    size_t nr_threads(const CompNode& comp_node) {
        check_the_same_comp_node(comp_node);
239 240 241 242 243 244
        return m_thread_pool ? m_thread_pool->nr_threads() : 1_z;
    }

    ThreadPool* get_thread_pool() { return m_thread_pool; }
};

245 246 247
using CompNodeBaseImpl = CpuCompNode::CompNodeBaseImpl;
using CompNodeNoRecorderImpl = CpuCompNode::CompNodeNoRecorderImpl;
using CompNodeRecorderImpl = CpuCompNode::CompNodeRecorderImpl;
248

249 250 251
//! ==================== CompNodeBaseImpl ======================
class CpuCompNode::CompNodeBaseImpl : public CpuDispatchableBase {
protected:
252 253
    Locator m_locator, m_locator_logical;

254 255 256 257 258 259
public:
    CompNodeBaseImpl(const Locator& locator, const Locator& locator_logical,
                     free_func_t fd, free_func_t fh)
            : CpuDispatchableBase(fd, fh),
              m_locator(locator),
              m_locator_logical(locator_logical) {}
260

261
    virtual ~CompNodeBaseImpl() {}
262

263 264
    void* mgb_aligned_alloc(size_t size) {
        auto alignment = get_mem_addr_alignment();
265
#ifdef WIN32
266
        return _aligned_malloc(size, alignment);
267
#elif defined(__ANDROID__) || defined(ANDROID)
268
        return memalign(alignment, size);
269
#else
270 271 272 273 274
        void* ptr = nullptr;
        auto err = posix_memalign(&ptr, alignment, size);
        mgb_assert(!err, "failed to malloc %zubytes with align %zu", size,
                   alignment);
        return ptr;
275
#endif
276
    }
277

278
    static void mgb_aligned_free(void* ptr) {
279
#ifdef WIN32
280
        _aligned_free(ptr);
281
#else
282
        ::free(ptr);
283
#endif
284
    }
285

286
    void* alloc_device(size_t size) override { return mgb_aligned_alloc(size); }
287

288
    void* alloc_host(size_t size) override { return mgb_aligned_alloc(size); }
289

290 291 292 293 294 295 296 297
    void copy_to_host(void* host_ptr, const void* device_ptr,
                      size_t size) override {
        // use lambda capture to avoid memory allocation in std::bind
        auto do_copy = [host_ptr, device_ptr, size]() {
            std::memcpy(host_ptr, device_ptr, size);
        };
        m_env.cpu_env().dispatch(do_copy);
    }
298

299 300 301 302 303 304 305 306
    void copy_to_device(void* device_ptr, const void* host_ptr,
                        size_t size) override {
        // use lambda capture to avoid memory allocation in std::bind
        auto do_copy = [device_ptr, host_ptr, size]() {
            std::memcpy(device_ptr, host_ptr, size);
        };
        m_env.cpu_env().dispatch(do_copy);
    }
307

308 309 310 311
    void peer_copy_to(Impl* dest_impl, void* dest, const void* src,
                      size_t size) override {
        dest_impl->copy_to_device(dest, src, size);
    }
312

313 314 315
    size_t get_mem_addr_alignment() override {
        return m_env.property().mem_alignment;
    }
316

317 318 319
    void dispatch(Task&& task) override {
        m_env.cpu_env().dispatch(std::move(task));
    }
320

321 322 323 324
    MemNode mem_node() override {
        // TODO: numa nodes
        return get_host_cpu_mem_node();
    }
325

326 327 328
    std::pair<size_t, size_t> get_mem_status_bytes() override {
        return sys::get_ram_status_bytes();
    }
329

330
    Locator locator() override { return m_locator; }
331

332
    Locator locator_logical() override { return m_locator_logical; }
333

334 335 336
    void add_callback(Task&& task) override {
        CpuDispatchableBase::add_callback(std::move(task));
    }
337

338
    virtual SeqRecorderImpl* cur_recorder() const = 0;
339
};
340 341

//! implementation of CPUDispatcher that is passed to megdnn via megcore
342
class CpuCompNode::WorkerQueue::DispatcherImpl final : public CPUDispatcher {
343 344
    std::atomic_size_t m_nr_task{0};
    std::shared_ptr<WorkerQueue> m_queue;
345 346 347
    //! DispatcherImpl only used by CompNodeRecorderImpl, but we still use
    //! CompNodeBaseImpl* because of incomplete type error
    CompNodeBaseImpl* const m_comp_node;
348 349 350

public:
    DispatcherImpl(const std::shared_ptr<WorkerQueue>& queue,
351
                   CompNodeBaseImpl* comp_node)
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
            : m_queue{queue}, m_comp_node{comp_node} {}

    void dispatch(Task&& task) override {
        if (auto recorder = m_comp_node->cur_recorder()) {
            recorder->dispatch(std::move(task), m_comp_node);
        } else {
            m_nr_task.fetch_add(1, std::memory_order_relaxed);
            auto kern = [task](size_t, size_t) { task(); };
            m_queue->add_task({kern, static_cast<size_t>(1_z)});
        }
    }

    void dispatch(MultiThreadingTask&& task, size_t parallelism) override {
        if (auto recorder = m_comp_node->cur_recorder()) {
            recorder->dispatch({std::move(task), parallelism}, m_comp_node);
        } else {
            m_nr_task.fetch_add(1, std::memory_order_relaxed);
            m_queue->add_task({std::move(task), parallelism});
        }
    }

    void sync() override {
        if (auto recorder = m_comp_node->cur_recorder()) {
            recorder->on_sync(m_comp_node);
        } else {
            m_queue->wait_all_task_finish();
        }
    }

    size_t nr_threads() override {
        if (auto recorder = m_comp_node->cur_recorder()) {
            return recorder->nr_threads(m_comp_node);
        } else {
            return m_queue->nr_threads();
        }
    }

    size_t get_nr_dispatched_tasks() const override { return m_nr_task; }

    void set_affinity(AffinityCallBack&& affinity_cb) override {
        auto thread_pool = m_queue->get_thread_pool();
        if (thread_pool) {
            thread_pool->set_affinity(affinity_cb);
        } else {
            auto affinity_run = [affinity_cb](size_t, size_t) {
                affinity_cb(0);
            };
            m_queue->add_task({affinity_run, 1_z});
        }
    }
};

//! implementation of InplaceCPUDispatcher
class InplaceCPUDispatcher final : public CPUDispatcher {
    std::atomic_size_t m_nr_task{0};
    ThreadPool* m_thread_pool = nullptr;
408 409 410
    //! InplaceCPUDispatcher may used by both type of compnodes, so
    //! m_comp_node's type should be base class.
    CompNodeBaseImpl* const m_comp_node;
411 412

public:
413
    InplaceCPUDispatcher(CompNodeBaseImpl* comp_node,
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
                         ThreadPool* thread_pool = nullptr)
            : m_thread_pool(thread_pool), m_comp_node(comp_node) {}

    void dispatch(Task&& task) override {
        if (auto recorder = m_comp_node->cur_recorder()) {
            recorder->dispatch(std::move(task), m_comp_node);
        } else if (m_thread_pool) {
            m_nr_task.fetch_add(1, std::memory_order_relaxed);
            auto kern = [task](size_t, size_t) { task(); };
            m_thread_pool->add_task({kern, static_cast<size_t>(1_z)});
        } else {
            m_nr_task.fetch_add(1, std::memory_order_relaxed);
            task();
        }
    }

    void dispatch(MultiThreadingTask&& task, size_t parallelism) override {
        if (auto recorder = m_comp_node->cur_recorder()) {
            recorder->dispatch({std::move(task), parallelism}, m_comp_node);
        } else if (m_thread_pool) {
            m_nr_task.fetch_add(1, std::memory_order_relaxed);
            m_thread_pool->add_task({task, parallelism});
436
        } else {
437
            m_nr_task.fetch_add(1, std::memory_order_relaxed);
438
            for (size_t i = 0; i < parallelism; i++) {
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
                task(i, 0);
            }
        }
    }

    size_t nr_threads() override {
        return m_thread_pool ? m_thread_pool->nr_threads() : 1_z;
    }

    void sync() override {
        if (auto recorder = m_comp_node->cur_recorder()) {
            recorder->on_sync(m_comp_node);
        } else if (m_thread_pool) {
            m_thread_pool->deactive();
        }
    }

    size_t get_nr_dispatched_tasks() const override { return m_nr_task; }

    void set_affinity(AffinityCallBack&& affinity_cb) override {
        if (auto recorder = m_comp_node->cur_recorder()) {
            recorder->get_thread_pool()->set_affinity(affinity_cb);
        } else if (m_thread_pool) {
            m_thread_pool->set_affinity(affinity_cb);
463
        } else {
464 465 466 467 468
            affinity_cb(0);
        }
    }
};

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
//! ==================== CompNodeNoRecorderImpl ======================
/**
 * \note: CompNodeNoRecorderImpl will use most implements in base including:
 * alloc_device, alloc_host, copy_to_host, copy_to_device, peer_copy_to,
 * add_callback ...
 */
class CpuCompNode::CompNodeNoRecorderImpl final : public CompNodeBaseImpl {
    MGB_DYN_TYPE_OBJ_FINAL_DECL;

public:
    //! ptr to default cpu, only used by check_global_finalized
    static CompNodeNoRecorderImpl* sm_default_cpu_comp_node_ptr;

    static void static_free_device(ImplBase* self, void* ptr) {
        static_cast<CompNodeNoRecorderImpl*>(self)->free_device(ptr);
484 485
    }

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
    static void static_free_host(ImplBase* self, void* ptr) {
        static_cast<CompNodeNoRecorderImpl*>(self)->free_host(ptr);
    }
    using CpuEventImpl = CpuDispatchableBase::EventImpl;

    CompNodeNoRecorderImpl(const Locator& locator,
                           const Locator& locator_logical)
            : CompNodeBaseImpl(locator, locator_logical, static_free_device,
                               static_free_host) {
        mgb_assert(
                locator.type == DeviceType::CPU &&
                        locator.device == Locator::DEVICE_CPU_DEFAULT,
                "CompNodeNoRecorder is only constructed On DEVICE_CPU_DEFAULT");
        auto cn = make_comp_node_from_impl(this);
        m_env.init_cpu({std::make_shared<InplaceCPUDispatcher>(this)}, cn);
        sm_default_cpu_comp_node_ptr = this;
    }

    ~CompNodeNoRecorderImpl() {
        m_env.fini();
        sm_default_cpu_comp_node_ptr = nullptr;
    }

    //! return whether global finalized, and print warning in such case
    bool check_global_finalized(const char* reason) {
        MGB_MARK_USED_VAR(reason);
        if (!sm_default_cpu_comp_node_ptr) {
            static std::atomic_flag warn_printed = ATOMIC_FLAG_INIT;
            if (!warn_printed.test_and_set()) {
                mgb_log_debug(
                        "cpu comp node method called after global finalize: "
                        "reason=%s",
                        reason);
            }
            return true;
521
        }
522
        return false;
523
    }
524

525 526 527 528
    void free_device(void* ptr) {
        if (check_global_finalized("free_device()")) {
            CompNodeBaseImpl::mgb_aligned_free(ptr);
            return;
529
        } else {
530 531
            auto do_free = [ptr]() { CompNodeBaseImpl::mgb_aligned_free(ptr); };
            m_env.cpu_env().dispatch(do_free);
532 533 534
        }
    }

535 536 537
    void free_host(void* ptr) {
        check_global_finalized("free_host()");
        return CompNodeBaseImpl::mgb_aligned_free(ptr);
538 539
    }

540 541 542 543 544 545 546 547 548 549 550 551 552
    std::unique_ptr<Event> create_event(size_t flags) override {
        return std::make_unique<CpuEventImpl>(this, flags);
    }

    void sync() override {}

    std::unique_ptr<CompNodeSeqRecorder> create_seq_recorder(
            cg::ComputingGraph*) override {
        mgb_assert(false, "default_cpu has no ability to record");
        return nullptr;
    }

    SeqRecorderImpl* cur_recorder() const override { return nullptr; }
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
MGB_DYN_TYPE_OBJ_FINAL_IMPL(CompNodeNoRecorderImpl);
CompNodeNoRecorderImpl* CompNodeNoRecorderImpl::sm_default_cpu_comp_node_ptr =
        nullptr;

//! ==================== CompNodeRecorderImpl ======================
class CpuCompNode::CompNodeRecorderImpl final : public CompNodeBaseImpl {
    MGB_DYN_TYPE_OBJ_FINAL_DECL;
    std::unique_ptr<ThreadPool> m_thread_pool;
    std::shared_ptr<WorkerQueue> m_worker_queue;

    //! used during comp node seq rec
    class CompSeqRecEventImpl final : public CpuDispatchableBase::EventImpl {
        void do_record() override {
            auto impl = static_cast<CompNodeRecorderImpl*>(m_comp_node_impl);
            if (auto rec = impl->cur_recorder()) {
                auto callback = [this]() {
                    incr_nr_req();
                    on_finish();
                };
                rec->dispatch_allow_after_sync(callback, m_comp_node_impl);
            } else {
                EventImpl::do_record();
            }
        }

        void do_device_wait_by(Impl*) override {
            mgb_throw(MegBrainError,
                      "device_wait() should not be called on events created "
                      "during "
                      "comp node seq recording");
        }
585

586 587 588 589 590
    public:
        using EventImpl::EventImpl;
    };

    class CpuEventImpl final : public CpuDispatchableBase::EventImpl {
591
#if MGB_HAVE_THREAD
592 593 594 595 596 597 598 599
        void host_wait_cv() override {
            CpuDispatchableBase::EventImpl::host_wait_cv();
            auto thread_pool =
                    static_cast<CompNodeRecorderImpl*>(m_comp_node_impl)
                            ->get_thread_pool();
            if (thread_pool) {
                thread_pool->deactive();
            }
600 601
        }
#endif
602 603 604 605 606 607 608 609 610 611 612 613 614 615
    public:
        using EventImpl::EventImpl;
    };

//! TODO: because the x-code bug, see
//! https://github.com/tensorflow/tensorflow/issues/18356
//! thread local is no support on IOS,
//! When update x-xode, this code should be deleted
#if !defined(IOS) && MGB_HAVE_THREAD
    static thread_local SeqRecorderImpl* sm_cur_recorder;
#else
    SeqRecorderImpl* sm_cur_recorder = nullptr;
#endif

616
public:
617 618 619
    static void static_free_device(ImplBase* self, void* ptr) {
        static_cast<CompNodeRecorderImpl*>(self)->free_device(ptr);
    }
620

621 622
    static void static_free_host(ImplBase* self, void* ptr) {
        static_cast<CompNodeRecorderImpl*>(self)->free_host(ptr);
623
    }
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656

    CompNodeRecorderImpl(const Locator& locator, const Locator& locator_logical,
                         const std::shared_ptr<WorkerQueue>& worker_queue)
            : CompNodeBaseImpl(locator, locator_logical, static_free_device,
                               static_free_host),
              m_worker_queue(worker_queue) {
        auto cn = make_comp_node_from_impl(this);
        if (locator.type == DeviceType::MULTITHREAD) {
            m_thread_pool = std::unique_ptr<ThreadPool>(
                    new ThreadPool(static_cast<size_t>(locator.nr_threads)));
            mgb_assert(m_thread_pool, "ThradPool create failed");
        }
        if (locator.type == DeviceType::CPU) {
            if (locator.device == Locator::DEVICE_CPU_DEFAULT) {
                m_env.init_cpu({std::make_shared<InplaceCPUDispatcher>(this)},
                               cn);
            } else {
                m_env.init_cpu({std::make_shared<WorkerQueue::DispatcherImpl>(
                                       m_worker_queue, this)},
                               cn);
            }
        } else if (locator.type == DeviceType::MULTITHREAD) {
            if (locator.device == Locator::DEVICE_MULTITHREAD_DEFAULT) {
                m_env.init_cpu({std::make_shared<InplaceCPUDispatcher>(
                                       this, m_thread_pool.get())},
                               cn);
            } else {
                m_worker_queue->attach_thread_pool(m_thread_pool.get());
                m_env.init_cpu({std::make_shared<WorkerQueue::DispatcherImpl>(
                                       m_worker_queue, this)},
                               cn);
            }
        }
657
    }
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827

    ~CompNodeRecorderImpl() {
        if (sm_cur_recorder) {
            sm_cur_recorder->stop();
        }
        if (m_worker_queue) {
            // synchronize before fini
            m_worker_queue->wait_all_task_finish();
        }
        m_env.fini();
        if (m_worker_queue) {
            // wait for new kernels dispatched in fini() (like free_device())
            m_worker_queue->wait_all_task_finish();
        }
    }

    ThreadPool* get_thread_pool() const { return m_thread_pool.get(); }

    //! return whether global finalized, and print warning in such case
    bool check_global_finalized(const char* reason) {
        MGB_MARK_USED_VAR(reason);
        if (!sm_pool) {
            static std::atomic_flag warn_printed = ATOMIC_FLAG_INIT;
            if (!warn_printed.test_and_set()) {
                mgb_log_debug(
                        "cpu comp node method called after global finalize: "
                        "reason=%s",
                        reason);
            }
            return true;
        }
        return false;
    }

    void* alloc_device(size_t size) override {
        if (sm_cur_recorder) {
            sm_cur_recorder->on_alloc(this);
        }
        return CompNodeBaseImpl::alloc_device(size);
    }

    void free_device(void* ptr) {
        if (sm_cur_recorder || check_global_finalized("free_device()")) {
            CompNodeBaseImpl::mgb_aligned_free(ptr);
            if (sm_cur_recorder) {
                sm_cur_recorder->on_free(this);
            }
            return;
        } else {
            auto do_free = [ptr]() { CompNodeBaseImpl::mgb_aligned_free(ptr); };
            m_env.cpu_env().dispatch(do_free);
        }
    }

    void* alloc_host(size_t size) override {
        if (m_worker_queue) {
            m_worker_queue->check_exception();
        }
        return CompNodeBaseImpl::alloc_host(size);
    }

    void free_host(void* ptr) {
        if (check_global_finalized("free_host()")) {
            CompNodeBaseImpl::mgb_aligned_free(ptr);
            return;
        }
        if (m_worker_queue) {
            m_worker_queue->check_exception();
        }
        CompNodeBaseImpl::mgb_aligned_free(ptr);
    }

    void copy_to_host(void* host_ptr, const void* device_ptr,
                      size_t size) override {
        if (m_worker_queue) {
            m_worker_queue->check_exception();
        }
        CompNodeBaseImpl::copy_to_host(host_ptr, device_ptr, size);
    }

    void copy_to_device(void* device_ptr, const void* host_ptr,
                        size_t size) override {
        if (m_worker_queue) {
            m_worker_queue->check_exception();
        }
        CompNodeBaseImpl::copy_to_device(device_ptr, host_ptr, size);
    }

    void peer_copy_to(Impl* dest_impl, void* dest, const void* src,
                      size_t size) override {
        //! copy to default_cpu
        if (dest_impl->same_type<CpuCompNode::CompNodeNoRecorderImpl>()) {
            CompNodeBaseImpl::peer_copy_to(dest_impl, dest, src, size);
            return;
        }

        if (!dest_impl->same_type<CpuCompNode::CompNodeRecorderImpl>()) {
            if (dest_impl->env().property().type == DeviceType::ATLAS) {
#if MGB_ATLAS
                dest_impl->copy_to_device(dest, src, size);
                return;
#else
                mgb_throw(MegBrainError,
                          "Atlas comp_node used but "
                          "MGB_ATLAS not enabled");
#endif
            } else if (dest_impl->env().property().type ==
                       DeviceType::CAMBRICON) {
#if MGB_CAMBRICON
                dest_impl->copy_to_device(dest, src, size);
                return;
#else
                mgb_throw(MegBrainError,
                          "Cambricon comp_node used but "
                          "MGB_CAMBRICON not enabled");
#endif
            }
            else {
                mgb_assert(locator().device == Locator::DEVICE_CPU_DEFAULT,
                           "currently only peer copy from default cpu comp "
                           "nodes "
                           "is implemented");
            }
        }
        dest_impl->copy_to_device(dest, src, size);
    }

    std::unique_ptr<Event> create_event(size_t flags) override {
        if (m_worker_queue) {
            m_worker_queue->check_exception();
        }
        if (sm_cur_recorder) {
            return std::make_unique<CompSeqRecEventImpl>(this, flags);
        } else {
            return std::make_unique<CpuEventImpl>(this, flags);
        }
    }

    void sync() override {
        if (sm_cur_recorder) {
            sm_cur_recorder->on_sync(this);
        } else if (m_worker_queue) {
            m_worker_queue->wait_all_task_finish();
        }
        if (m_thread_pool) {
            m_thread_pool->deactive();
        }
    }

    std::unique_ptr<CompNodeSeqRecorder> create_seq_recorder(
            cg::ComputingGraph*) override {
        return std::make_unique<SeqRecorderImpl>(&sm_cur_recorder,
                                                 m_thread_pool.get(), this);
    }

    SeqRecorderImpl* cur_recorder() const override { return sm_cur_recorder; }

    void add_callback(Task&& task) override {
        if (!check_global_finalized("add_callback()")) {
            CompNodeBaseImpl::add_callback(std::move(task));
        } else {
            task();
        }
    }
};
MGB_DYN_TYPE_OBJ_FINAL_IMPL(CompNodeRecorderImpl);
#if !defined(IOS) && MGB_HAVE_THREAD
thread_local CpuCompNode::SeqRecorderImpl*
        CompNodeRecorderImpl::sm_cur_recorder = nullptr;
#endif
828 829 830 831

/* ======================== CpuCompNode ======================== */
struct CpuCompNode::Pool {
    static constexpr int MAX_NR_COMP_NODE = 1024;
832 833
    struct CompNodeRecorderImplDeleter {
        void operator()(CompNodeRecorderImpl* p) { p->~CompNodeRecorderImpl(); }
834 835 836 837 838
    };

    std::recursive_mutex mtx;
    // use global memory pool to ensuare object memory accessible even after
    // global finalize
839 840 841
    std::aligned_storage_t<sizeof(CompNodeRecorderImpl),
                           alignof(CompNodeRecorderImpl)>
            impl_storage[MAX_NR_COMP_NODE];
842 843
    size_t nr_used_impl_storage = 0;

844 845 846 847 848
    std::unordered_map<
            CompNode::LocatorPairHashKey,
            std::unique_ptr<CompNodeRecorderImpl, CompNodeRecorderImplDeleter>,
            CompNode::LocatorPairHashKey::Hash>
            locator2impl;
849
    ThinHashMap<std::pair<int, int>, std::weak_ptr<WorkerQueue>> physical2queue;
850 851 852 853 854
    std::unordered_map<
            CompNode::LocatorPairHashKey,
            std::unique_ptr<CompNodeRecorderImpl, CompNodeRecorderImplDeleter>,
            CompNode::LocatorPairHashKey::Hash>
            locator2impl_multi_thread;
855 856 857 858 859 860
    ThinHashMap<std::pair<int, int>, std::weak_ptr<WorkerQueue>>
            physical2queue_multithead;
};
CpuCompNode::Pool* CpuCompNode::sm_pool;
Spinlock CpuCompNode::sm_pool_mtx;

861
void CpuCompNode::foreach (thin_function<void(CompNode)> callback) {
862 863 864
    if (!sm_pool)
        return;

865
    for (size_t i = 0;; ++i) {
866 867 868 869 870 871
        CompNode cur;
        {
            MGB_LOCK_GUARD(sm_pool->mtx);
            if (i >= sm_pool->nr_used_impl_storage)
                return;
            cur = make_comp_node_from_impl(
872 873
                    reinterpret_cast<CompNodeRecorderImpl*>(
                            &sm_pool->impl_storage[i]));
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
        }
        callback(cur);
    }
}

void CpuCompNode::finalize() {
    if (sm_pool) {
        sync_all();

        sm_pool->~Pool();
        sm_pool = nullptr;
    }
}

size_t CpuCompNode::get_device_count() {
    return sys::get_cpu_count();
}

CpuCompNode::Impl* CpuCompNode::load_cpu(Locator locator,
                                         Locator locator_logical) {
#if !MGB_HAVE_THREAD
    // use only cpu:default and cpu0:1023 comp node when threading is disabled
    mgb_assert(locator.device == Locator::DEVICE_CPU_DEFAULT ||
               (locator.device == 0 && locator.stream == 1023));
    locator_logical = {locator_logical.type, locator.device, locator.stream};
#endif
    {
        MGB_LOCK_GUARD(sm_pool_mtx);
        if (!sm_pool) {
            // use static storage so object can be safely accessed even after
            // global finalize
            static std::aligned_storage_t<sizeof(Pool), alignof(Pool)> storage;
906
            sm_pool = new (&storage) Pool;
907 908 909 910 911 912 913 914 915 916 917
        }
    }
    mgb_assert(locator.device >= 0 ||
                       (locator.device == Locator::DEVICE_CPU_DEFAULT &&
                        locator.stream == 0) ||
                       locator.device == Locator::DEVICE_MULTITHREAD_DEFAULT,
               "failed to load cpu for device:%d stream:%d", locator.device,
               locator.stream);
    MGB_LOCK_GUARD(sm_pool->mtx);

    // encode both device ID and type into a int
918 919 920
    mgb_assert(locator_logical.device >= -1 ||
               locator_logical.device <= Locator::DEVICE_CPU_DEFAULT);
    if (locator_logical.type != CompNode::DeviceType::UNSPEC) {
921 922 923 924
        mgb_assert(locator_logical.type == CompNode::DeviceType::CPU ||
                   locator_logical.type == CompNode::DeviceType::MULTITHREAD);
    }
    if (locator.type == DeviceType::CPU) {
925 926
        auto&& pqueue_weak =
                sm_pool->physical2queue[{locator.device, locator.stream}];
927 928 929 930 931
        auto pqueue = pqueue_weak.lock();
        if (!pqueue) {
            pqueue = std::make_shared<WorkerQueue>(locator);
            pqueue_weak = pqueue;
        }
932
        auto&& pimpl = sm_pool->locator2impl[{locator, locator_logical}];
933 934 935 936 937 938
        if (!pimpl) {
            mgb_assert(sm_pool->nr_used_impl_storage < Pool::MAX_NR_COMP_NODE,
                       "too many cpu comp nodes; max %d allowed",
                       Pool::MAX_NR_COMP_NODE);
            pimpl.reset(new (
                    &sm_pool->impl_storage[sm_pool->nr_used_impl_storage++])
939 940
                                CompNodeRecorderImpl{locator, locator_logical,
                                                     pqueue});
941 942 943 944 945 946
        }
        log_comp_node_created(locator, locator_logical);
        return pimpl.get();
    } else {
        mgb_assert(locator.type == DeviceType::MULTITHREAD);
        auto&& pqueue_weak = sm_pool->physical2queue_multithead[{
947
                locator.device, locator.nr_threads}];
948 949 950 951 952
        auto pqueue = pqueue_weak.lock();
        if (!pqueue) {
            pqueue = std::make_shared<WorkerQueue>(locator);
            pqueue_weak = pqueue;
        }
953 954
        auto&& pimpl =
                sm_pool->locator2impl_multi_thread[{locator, locator_logical}];
955 956 957 958 959 960
        if (!pimpl) {
            mgb_assert(sm_pool->nr_used_impl_storage < Pool::MAX_NR_COMP_NODE,
                       "too many cpu multithread comp nodes; max %d allowed",
                       Pool::MAX_NR_COMP_NODE);
            pimpl.reset(new (
                    &sm_pool->impl_storage[sm_pool->nr_used_impl_storage++])
961 962
                                CompNodeRecorderImpl{locator, locator_logical,
                                                     pqueue});
963 964 965 966 967 968 969 970 971 972 973
        }
        log_comp_node_created(locator, locator_logical);
        return pimpl.get();
    }
}

void CpuCompNode::sync_all() {
    if (!sm_pool)
        return;

    MGB_LOCK_GUARD(sm_pool->mtx);
974
    for (auto&& i : sm_pool->locator2impl)
975
        i.second->sync();
976
    for (auto&& i : sm_pool->locator2impl_multi_thread)
977 978 979 980
        i.second->sync();
}

/* ======================== CompNode methods ========================  */
981 982 983 984 985 986
// CompNode get by default_cpu() is different from the CompNode which is
// produced by CompNode::load("cpu:default")
// default_cpu() is used for static infer and it is not allowed to send up the
// compute kernel
// CompNode::load("cpu:default") is "inplace cpu" which is in the
// CpuCompNode::Pool
987
CompNode CompNode::default_cpu() {
M
Megvii Engine Team 已提交
988
    static Locator locator{DeviceType::CPU, Locator::DEVICE_CPU_DEFAULT, {-1}};
989
    static CompNodeNoRecorderImpl impl{locator, locator};
990 991 992 993 994 995 996 997 998 999 1000
    return &impl;
}

bool CompNode::enable_affinity_for_cpu(bool flag) {
    bool old = enable_affinity;
    enable_affinity = flag;
    return old;
}

/* ======================== EventImpl ========================  */
double CpuCompNode::CpuDispatchableBase::EventImpl::do_elapsed_time_until(
1001 1002
        EventImplHelper& end) {
    auto&& f1 = static_cast<EventImpl&>(end).m_prev_finish_time;
1003 1004 1005 1006 1007
    return m_prev_finish_time.time_until_secs(f1);
}

#if MGB_HAVE_THREAD
void CpuCompNode::CpuDispatchableBase::EventImpl::do_device_wait_by(
1008
        Impl* cn_impl) {
1009 1010 1011
    {
        auto locator = m_comp_node_impl->locator();
        if (locator.device == Locator::DEVICE_CPU_DEFAULT &&
1012
            !static_cast<CpuCompNode::CompNodeRecorderImpl*>(m_comp_node_impl)
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
                     ->cur_recorder()) {
            auto v0 = m_record_nr_req.load(std::memory_order_relaxed),
                 v1 = m_record_nr_finish.load(std::memory_order_relaxed);
            mgb_assert(v0 && v0 == v1,
                       "event on cpu:default hasn't been recorded inplace.");
            return;
        }
    }

    {
        auto type = cn_impl->env().property().type;
1024 1025 1026 1027 1028 1029 1030
        mgb_throw_if(
                type != CompNode::DeviceType::CPU &&
                        type != CompNode::DeviceType::CUDA
                        && type != CompNode::DeviceType::ATLAS &&
                        type != CompNode::DeviceType::CAMBRICON,
                MegBrainError,
                "currently CPU can only wait for CPU, CUDA, ATLAS, CAMBRICON"
1031 1032 1033
        );
    }

1034 1035 1036 1037 1038 1039 1040
    if (cn_impl->env().property().type == CompNode::DeviceType::ATLAS) {
#if MGB_ATLAS
        return m_comp_node_impl->sync();
#else
        mgb_throw(MegBrainError,
                  "Atlas comp_node used but MGB_ATLAS not enabled");
#endif
1041 1042
    } else if (cn_impl->env().property().type ==
               CompNode::DeviceType::CAMBRICON) {
1043 1044 1045 1046 1047 1048
#if MGB_CAMBRICON
        return m_comp_node_impl->sync();
#else
        mgb_throw(MegBrainError,
                  "Cambricon comp_node used but MGB_CAMBRICON not enabled");
#endif
1049
    }
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097

    auto version = m_record_nr_req.load(std::memory_order_relaxed);
    mgb_assert(version, "device wait on non-recorded event");

    auto waiter = [this, version]() {
        while (m_record_nr_finish.load(std::memory_order_acquire) < version) {
            std::unique_lock<std::mutex> lk{m_dev_wait_mtx};
            if (m_record_nr_finish.load(std::memory_order_acquire) >= version) {
                break;
            }
            m_dev_wait_cv.wait(lk);
        }
        m_dev_wait_nr_waiter.fetch_sub(1, std::memory_order_release);
    };
    m_dev_wait_nr_waiter.fetch_add(1, std::memory_order_release);
    cn_impl->add_callback(waiter);
}

void CpuCompNode::CpuDispatchableBase::EventImpl::do_record() {
    incr_nr_req();
    auto call_on_finish = [this]() { on_finish(); };
    static_cast<CpuDispatchableBase*>(m_comp_node_impl)
            ->dispatch(call_on_finish);
}

void CpuCompNode::CpuDispatchableBase::EventImpl::on_finish() {
    if (m_create_flags & Flags::NEED_TIMER) {
        auto v0 = m_record_nr_finish.load(std::memory_order_relaxed) + 1,
             v1 = m_record_nr_req.load(std::memory_order_relaxed);
        if (v0 == v1) {
            m_prev_finish_time = RealTimer::get_time();
        }
    }

    m_record_nr_finish.fetch_add(1, std::memory_order_release);
    if (m_dev_wait_nr_waiter.load(std::memory_order_acquire)) {
        MGB_LOCK_GUARD(m_dev_wait_mtx);
        m_dev_wait_cv.notify_all();
    }
}

bool CpuCompNode::CpuDispatchableBase::EventImpl::do_finished() {
    auto v0 = m_record_nr_req.load(std::memory_order_relaxed);
    auto v1 = m_record_nr_finish.load(std::memory_order_acquire);
    return v0 == v1;
}

void CpuCompNode::CpuDispatchableBase::EventImpl::host_wait_cv() {
1098 1099
    for (size_t i = 0, it = SCQueueSynchronizer::get_default_max_spin() / 20;
         i < it; ++i) {
1100 1101 1102 1103 1104 1105
        if (finished()) {
            return;
        }
    }

    m_dev_wait_nr_waiter.fetch_add(1, std::memory_order_release);
1106
    for (;;) {
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
        std::unique_lock<std::mutex> lock{m_dev_wait_mtx};
        if (finished()) {
            break;
        }
        m_dev_wait_cv.wait(lock);
    }
    m_dev_wait_nr_waiter.fetch_sub(1, std::memory_order_release);
}

CpuCompNode::CpuDispatchableBase::EventImpl::~EventImpl() noexcept {
    auto check_all_finished = [this]() {
        return do_finished() &&
1119
               !m_dev_wait_nr_waiter.load(std::memory_order_acquire);
1120 1121
    };
    if (!check_all_finished()) {
1122 1123 1124 1125
        mgb_log_debug(
                "event %p has unfinished callbacks when destructed; "
                "waiting ...",
                this);
1126 1127 1128 1129 1130
        while (!check_all_finished()) {
            std::this_thread::yield();
        }
    }
}
1131
#else  // MGB_HAVE_THREAD
1132

1133
void CpuCompNode::CpuDispatchableBase::EventImpl::host_wait_cv() {}
1134

1135
void CpuCompNode::CpuDispatchableBase::EventImpl::do_device_wait_by(Impl*) {}
1136 1137 1138 1139 1140 1141 1142

void CpuCompNode::CpuDispatchableBase::EventImpl::do_record() {
    if (m_create_flags & Flags::NEED_TIMER) {
        m_prev_finish_time = RealTimer::get_time();
    }
}

1143
void CpuCompNode::CpuDispatchableBase::EventImpl::on_finish() {}
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153

bool CpuCompNode::CpuDispatchableBase::EventImpl::do_finished() {
    return true;
}

CpuCompNode::CpuDispatchableBase::EventImpl::~EventImpl() noexcept = default;

#endif  // MGB_HAVE_THREAD

// vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}