CustomStackTrace.h 4.7 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 17

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

#include <stack>
Y
Yu Yang 已提交
18 19 20
#include <thread>
#include <unordered_map>
#include <functional>
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 {
Z
zhangjinchao01 已提交
52 53
public:
  /**
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 62
  void pop(const T& item) {
    pushing() = false;
    auto& s = this->stack();
    if (item == s.top()) {
      s.pop();
    }
Z
zhangjinchao01 已提交
63
  }
Y
Yu Yang 已提交
64

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

Z
zhangjinchao01 已提交
75
  /**
Y
Yu Yang 已提交
76 77
   * @brief return true if all thread's stack is empty.
   * @return true if empty
Z
zhangjinchao01 已提交
78
   */
Y
Yu Yang 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
  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*/,
98 99
                             bool* /*isPushing*/,
                             const T& /*item*/)> DumpCallback;
Y
Yu Yang 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

  /**
   * 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 已提交
123
  }
Y
Yu Yang 已提交
124

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

private:
Y
Yu Yang 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
  /**
   * 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() {
162
    return this->getThreadLocal(this->logStack_, this->stackBuffers_);
Y
Yu Yang 已提交
163 164 165 166 167 168
  }

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

private:
  mutable std::mutex mtx_;

175 176
  std::unordered_map<std::thread::id, std::stack<T>*> stackBuffers_;
  std::unordered_map<std::thread::id, bool*> pushingBuffers_;
Y
Yu Yang 已提交
177
  ThreadLocal<bool> isPushing_;
178
  ThreadLocal<std::stack<T>> logStack_;
Z
zhangjinchao01 已提交
179 180 181 182
};

extern CustomStackTrace<std::string> gLayerStackTrace;

Y
Yu Yang 已提交
183 184 185 186 187
/**
 * @brief Install a failure handler to print layer stack when error.
 */
extern void installLayerStackTracer();

Z
zhangjinchao01 已提交
188
}  // namespace paddle