CustomStackTrace.h 4.8 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

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. */

#pragma once

Y
Yu Yang 已提交
17
#include <functional>
Z
zhangjinchao01 已提交
18
#include <stack>
Y
Yu Yang 已提交
19 20
#include <thread>
#include <unordered_map>
Z
zhangjinchao01 已提交
21 22 23 24 25 26

#include "ThreadLocal.h"

namespace paddle {

/**
27 28
 * A ThreadLocal stack for tracing train/test process.
 * (More details of ThreadLocal can be find
Z
zhangjinchao01 已提交
29
 * in the comments of ThreadLocal class.)
30
 *
Z
zhangjinchao01 已提交
31 32
 * For example.
 * @code{.cpp}
33
 *
Z
zhangjinchao01 已提交
34 35 36
 * paddle::CustomStackTrace<std::string> stack;
 * for (auto& layer : layers){
 *   stack.push(layer->getName());
Y
Yu Yang 已提交
37
 *   layer->forward();
Z
zhangjinchao01 已提交
38
 * }
Y
Yu Yang 已提交
39 40 41 42 43
 *
 * stack.pop("");  // mark under pop stage.
 *
 * for (auto it = layers.rbegin(); it != layers.rend(); ++it){
 *   auto& layer = *it;
Z
zhangjinchao01 已提交
44 45 46 47 48 49 50
 *   layer->backward(passType);
 *   stack.pop(layer->getName());
 * }
 *
 * @endcode
 */
template <typename T>
51
class CustomStackTrace {
W
Wu Yi 已提交
52
 public:
Z
zhangjinchao01 已提交
53
  /**
Y
Yu Yang 已提交
54 55
   * @brief Pop out an item from the top of the stack if item == top.
   *        Else, just set status to popping.
Z
zhangjinchao01 已提交
56
   */
Y
Yu Yang 已提交
57 58 59 60 61
  void pop(const T& item) {
    auto& s = this->stack();
    if (item == s.top()) {
      s.pop();
    }
Z
zhangjinchao01 已提交
62
  }
Y
Yu Yang 已提交
63

X
xuwei06 已提交
64 65 66 67 68
  /**
   * @brief Indicate whether we are at forward or backward stage of computation
   */
  void set_stage(bool isForward) { pushing() = isForward; }

Z
zhangjinchao01 已提交
69
  /**
Y
Yu Yang 已提交
70
   * @brief clear current thread stack.
Z
zhangjinchao01 已提交
71
   */
Y
Yu Yang 已提交
72 73 74 75
  void clear() {
    auto& s = stack();
    while (!s.empty()) {
      s.pop();
Z
zhangjinchao01 已提交
76 77
    }
  }
Y
Yu Yang 已提交
78

Z
zhangjinchao01 已提交
79
  /**
Y
Yu Yang 已提交
80 81
   * @brief return true if all thread's stack is empty.
   * @return true if empty
Z
zhangjinchao01 已提交
82
   */
Y
Yu Yang 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
  bool empty() const {
    std::lock_guard<std::mutex> g(this->mtx_);
    for (auto p : this->stackBuffers_) {
      std::stack<T>& s = *p.second;
      if (!s.empty()) {
        return false;
      }
    }
    return true;
  }

  /**
   * @brief DumpCallback Type. It will be invoked many times by dump method.
   *
   * The first parameter is stack thread id.
   * The second parameter is the last action of stack is push or not.
   * The third parameter is the item in stack.
   */
  typedef std::function<void(const std::thread::id& /*threadId*/,
102
                             bool* /*isPushing*/,
Y
Yu Yang 已提交
103 104
                             const T& /*item*/)>
      DumpCallback;
Y
Yu Yang 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

  /**
   * Dump all thread stack, and all stack will be cleared.
   */
  void dump(const DumpCallback& callback, bool onlyCurrentThread = false) {
    std::lock_guard<std::mutex> g(this->mtx_);
    for (auto p : this->stackBuffers_) {
      std::thread::id tid = p.first;
      if (onlyCurrentThread && tid != std::this_thread::get_id()) {
        continue;
      }
      std::stack<T>& s = *p.second;
      bool* isPush = nullptr;
      auto it = this->pushingBuffers_.find(tid);
      if (it != this->pushingBuffers_.end()) {
        isPush = it->second;
      }

      while (!s.empty()) {
        callback(tid, isPush, s.top());
        s.pop();
      }
    }
Z
zhangjinchao01 已提交
128
  }
Y
Yu Yang 已提交
129

Z
zhangjinchao01 已提交
130
  /**
Y
Yu Yang 已提交
131
   * @brief Push item to current thread stack.
Z
zhangjinchao01 已提交
132
   */
Y
Yu Yang 已提交
133 134 135 136
  void push(const T& item) {
    pushing() = true;
    auto& p = this->stack();
    p.push(item);
Z
zhangjinchao01 已提交
137 138
  }

W
Wu Yi 已提交
139
 private:
Y
Yu Yang 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
  /**
   * Get thread local attribute, and save them into a map (threadId => TYPE*)
   *
   * @tparam TYPE thread local attribute type.
   * @param threadLocal Thread Local object.
   * @param buffers a map from threadId to TYPE*
   */
  template <typename TYPE>
  inline TYPE& getThreadLocal(
      ThreadLocal<TYPE>& threadLocal,
      std::unordered_map<std::thread::id, TYPE*>& buffers) {
    TYPE* retv = threadLocal.get(false);
    if (retv) {
      return *retv;
    } else {
      std::lock_guard<std::mutex> guard(this->mtx_);
      retv = threadLocal.get();
      auto id = std::this_thread::get_id();
      buffers.insert({id, retv});
      return *retv;
    }
  }

  /**
   * @brief Get thread local stack reference.
   */
  std::stack<T>& stack() {
167
    return this->getThreadLocal(this->logStack_, this->stackBuffers_);
Y
Yu Yang 已提交
168 169 170 171 172 173
  }

  /**
   * @brief Get thread local pushing flag.
   */
  bool& pushing() {
174
    return this->getThreadLocal(this->isPushing_, this->pushingBuffers_);
Y
Yu Yang 已提交
175 176
  }

W
Wu Yi 已提交
177
 private:
Y
Yu Yang 已提交
178 179
  mutable std::mutex mtx_;

180 181
  std::unordered_map<std::thread::id, std::stack<T>*> stackBuffers_;
  std::unordered_map<std::thread::id, bool*> pushingBuffers_;
Y
Yu Yang 已提交
182
  ThreadLocal<bool> isPushing_;
183
  ThreadLocal<std::stack<T>> logStack_;
Z
zhangjinchao01 已提交
184 185 186 187
};

extern CustomStackTrace<std::string> gLayerStackTrace;

Y
Yu Yang 已提交
188 189 190 191 192
/**
 * @brief Install a failure handler to print layer stack when error.
 */
extern void installLayerStackTracer();

Z
zhangjinchao01 已提交
193
}  // namespace paddle