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

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 27 28 29 30 31 32 33 34 35 36

#include "ThreadLocal.h"

namespace paddle {

/**
 * A ThreadLocal stack for tracing train/test process. 
 * (More details of ThreadLocal can be find 
 * in the comments of ThreadLocal class.)
 * 
 * For example.
 * @code{.cpp}
 * 
 * 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 51 52 53
 *   layer->backward(passType);
 *   stack.pop(layer->getName());
 * }
 *
 * @endcode
 */
template <typename T>
class CustomStackTrace{
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 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
  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*/,
                              bool* /*isPushing*/,
                              const T& /*item*/)> DumpCallback;

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

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

private:
Y
Yu Yang 已提交
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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
  /**
   * 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() {
    return this->getThreadLocal(this->logStack_,
                                this->stackBuffers_);
  }

  /**
   * @brief Get thread local pushing flag.
   */
  bool& pushing() {
    return this->getThreadLocal(this->isPushing_,
                                this->pushingBuffers_);
  }

private:
  mutable std::mutex mtx_;

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

extern CustomStackTrace<std::string> gLayerStackTrace;

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

Z
zhangjinchao01 已提交
191
}  // namespace paddle