Caffe2 - C++ API
A deep learning, cross platform ML framework
lstm_unit_op.h
1 #ifndef CAFFE2_OPERATORS_LSTM_UNIT_OP_H_
2 #define CAFFE2_OPERATORS_LSTM_UNIT_OP_H_
3 
4 #include "caffe2/core/context.h"
5 #include "caffe2/core/operator.h"
6 #include "caffe2/utils/conversions.h"
7 
8 namespace caffe2 {
9 namespace detail {
10 template <typename T>
11 inline T sigmoid(T x) {
12  return 1. / (1. + exp(-x));
13 }
14 
15 template <typename T>
16 inline T host_tanh(T x) {
17  return 2. * sigmoid(2. * x) - 1.;
18 }
19 
20 template <typename T, typename Context>
21 void LSTMUnit(
22  int N,
23  int D,
24  int t,
25  const T* H_prev,
26  const T* C_prev,
27  const T* X,
28  const int32_t* seqLengths,
29  bool drop_states,
30  T* C,
31  T* H,
32  const float forget_bias,
33  Context* /*context*/) {
34  for (int n = 0; n < N; ++n) {
35  const bool valid = seqLengths == nullptr || t < seqLengths[n];
36 
37  for (int d = 0; d < D; ++d) {
38  if (!valid) {
39  if (drop_states) {
40  H[d] = 0;
41  C[d] = 0;
42  } else {
43  H[d] = H_prev[d];
44  C[d] = C_prev[d];
45  }
46  } else {
47  const T i = sigmoid(X[d]);
48  const T f = sigmoid(X[1 * D + d] + convert::To<float, T>(forget_bias));
49  const T o = sigmoid(X[2 * D + d]);
50  const T g = host_tanh(X[3 * D + d]);
51  const T c_prev = C_prev[d];
52  const T c = f * c_prev + i * g;
53  C[d] = c;
54  const T host_tanh_c = host_tanh(c);
55  H[d] = o * host_tanh_c;
56  }
57  }
58  H_prev += D;
59  C_prev += D;
60  X += 4 * D;
61  C += D;
62  H += D;
63  }
64 }
65 
66 template <typename T, typename Context>
67 void LSTMUnitGradient(
68  int N,
69  int D,
70  int t,
71  const T* C_prev,
72  const T* X,
73  const int32_t* seqLengths,
74  const T* C,
75  const T* H,
76  const T* C_diff,
77  const T* H_diff,
78  bool drop_states,
79  T* H_prev_diff,
80  T* C_prev_diff,
81  T* X_diff,
82  const float forget_bias,
83  Context* /*context*/) {
84  for (int n = 0; n < N; ++n) {
85  const bool valid = seqLengths == nullptr || t < seqLengths[n];
86 
87  for (int d = 0; d < D; ++d) {
88  T* c_prev_diff = C_prev_diff + d;
89  T* h_prev_diff = H_prev_diff + d;
90  T* i_diff = X_diff + d;
91  T* f_diff = X_diff + 1 * D + d;
92  T* o_diff = X_diff + 2 * D + d;
93  T* g_diff = X_diff + 3 * D + d;
94 
95  if (!valid) {
96  if (drop_states) {
97  *h_prev_diff = 0;
98  *c_prev_diff = 0;
99  } else {
100  *h_prev_diff = H_diff[d];
101  *c_prev_diff = C_diff[d];
102  }
103  *i_diff = 0;
104  *f_diff = 0;
105  *o_diff = 0;
106  *g_diff = 0;
107  } else {
108  const T i = sigmoid(X[d]);
109  const T f = sigmoid(X[1 * D + d] + convert::To<float, T>(forget_bias));
110  const T o = sigmoid(X[2 * D + d]);
111  const T g = host_tanh(X[3 * D + d]);
112  const T c_prev = C_prev[d];
113  const T c = C[d];
114  const T host_tanh_c = host_tanh(c);
115  const T c_term_diff = C_diff[d] + H_diff[d] * o * (1 - host_tanh_c * host_tanh_c);
116  *c_prev_diff = c_term_diff * f;
117  *h_prev_diff = 0; // not used in 'valid' case
118  *i_diff = c_term_diff * g * i * (1 - i);
119  *f_diff = c_term_diff * c_prev * f * (1 - f);
120  *o_diff = H_diff[d] * host_tanh_c * o * (1 - o);
121  *g_diff = c_term_diff * i * (1 - g * g);
122  }
123  }
124  C_prev += D;
125  X += 4 * D;
126  C += D;
127  H += D;
128  C_diff += D;
129  H_diff += D;
130  X_diff += 4 * D;
131  H_prev_diff += D;
132  C_prev_diff += D;
133  }
134 }
135 } // namespace detail
136 
137 template <typename Context>
138 class LSTMUnitOp : public Operator<Context> {
139  public:
140  explicit LSTMUnitOp(const OperatorDef& operator_def, Workspace* ws)
141  : Operator<Context>(operator_def, ws),
142  forget_bias_(static_cast<float>(
143  this->template GetSingleArgument<float>("forget_bias", 0.0))),
144  sequence_lengths_(
145  this->template GetSingleArgument<bool>("sequence_lengths", true)),
146  drop_states_(
147  this->template GetSingleArgument<bool>("drop_states", false)) {}
148  USE_OPERATOR_CONTEXT_FUNCTIONS;
150 
151  template <typename T>
152  bool DoRunWithType() {
153  // handle potentially-missing sequence lengths input
154  const size_t TIMESTEP = SEQ_LENGTHS + (sequence_lengths_ ? 1 : 0);
155 
156  // Extract N
157  const auto N = Input(CELL_T_M_1).size(1);
158 
159  // Gates: 1xNxG
160  const auto G = Input(GATES).size(2);
161  const auto D = Input(CELL_T_M_1).size(2);
162 
163  CAFFE_ENFORCE_EQ(4 * D, G);
164  const auto* H_prev = Input(HIDDEN_T_M_1).template data<T>();
165  const auto* C_prev = Input(CELL_T_M_1).template data<T>();
166  const auto* X = Input(GATES).template data<T>();
167 
168  const int32_t* seqLengths = nullptr;
169  if (sequence_lengths_) {
170  CAFFE_ENFORCE_EQ(Input(SEQ_LENGTHS).numel(), N);
171  seqLengths = Input(SEQ_LENGTHS).template data<int32_t>();
172  }
173 
174  const auto t = static_cast<OperatorBase*>(this)
175  ->Input<Tensor>(TIMESTEP, CPU)
176  .template data<int32_t>()[0];
177  Output(CELL_T)->ResizeLike(Input(CELL_T_M_1));
178  auto* C = Output(CELL_T)->template mutable_data<T>();
179  Output(HIDDEN_T)->ResizeLike(Input(CELL_T_M_1));
180  auto* H = Output(HIDDEN_T)->template mutable_data<T>();
181  detail::LSTMUnit<T, Context>(
182  N,
183  D,
184  t,
185  H_prev,
186  C_prev,
187  X,
188  seqLengths,
189  drop_states_,
190  C,
191  H,
192  forget_bias_,
193  &context_);
194  return true;
195  }
196 
197  bool RunOnDevice() override {
198  return DoRunWithType<float>();
199  }
200 
201  protected:
202  INPUT_TAGS(HIDDEN_T_M_1, CELL_T_M_1, GATES, SEQ_LENGTHS);
203  // additional input tags are determined dynamically based on whether
204  // sequence_lengths is present.
205  OUTPUT_TAGS(HIDDEN_T, CELL_T);
206 
207  float forget_bias_;
208  bool sequence_lengths_;
209 
210  private:
211  bool drop_states_;
212 };
213 
214 template <typename Context>
215 class LSTMUnitGradientOp : public Operator<Context> {
216  public:
217  template <class... Args>
218  explicit LSTMUnitGradientOp(Args&&... args)
219  : Operator<Context>(std::forward<Args>(args)...),
220  forget_bias_(static_cast<float>(
221  this->template GetSingleArgument<float>("forget_bias", 0.0))),
222  sequence_lengths_(
223  this->template GetSingleArgument<bool>("sequence_lengths", true)),
224  drop_states_(
225  this->template GetSingleArgument<bool>("drop_states", false)) {}
226  USE_OPERATOR_CONTEXT_FUNCTIONS;
227 
228  template <typename T>
229  bool DoRunWithType() {
230  // handle potentially-missing sequence lengths input
231  const size_t inputOffset = SEQ_LENGTHS + (sequence_lengths_ ? 1 : 0);
232  const size_t TIMESTEP = inputOffset;
233  const size_t HIDDEN_T = inputOffset + 1;
234  const size_t CELL_T = inputOffset + 2;
235  const size_t HIDDEN_T_GRAD = inputOffset + 3;
236  const size_t CELL_T_GRAD = inputOffset + 4;
237 
238  // Extract N
239  const auto N = Input(CELL_T_M_1).size(1);
240 
241  // Gates: 1xNxG
242  const auto G = Input(GATES).size(2);
243  const auto D = Input(CELL_T_M_1).size(2);
244 
245  CAFFE_ENFORCE_EQ(4 * D, G);
246  const auto* C_prev = Input(CELL_T_M_1).template data<T>();
247  const auto* X = Input(GATES).template data<T>();
248  const auto t = static_cast<OperatorBase*>(this)
249  ->Input<Tensor>(TIMESTEP, CPU)
250  .template data<int32_t>()[0];
251  const auto* C = Input(CELL_T).template data<T>();
252  const auto* H = Input(HIDDEN_T).template data<T>();
253  const auto* C_diff = Input(CELL_T_GRAD).template data<T>();
254  const auto* H_diff = Input(HIDDEN_T_GRAD).template data<T>();
255 
256  const int32_t* seqLengths = nullptr;
257  if (sequence_lengths_) {
258  CAFFE_ENFORCE_EQ(Input(SEQ_LENGTHS).numel(), N);
259  seqLengths = Input(SEQ_LENGTHS).template data<int32_t>();
260  }
261 
262  Output(HIDDEN_T_M_1_GRAD)->ResizeLike(Input(HIDDEN_T_M_1));
263  auto* H_prev_diff = Output(HIDDEN_T_M_1_GRAD)->template mutable_data<T>();
264  Output(CELL_T_M_1_GRAD)->ResizeLike(Input(CELL_T_M_1));
265  auto* C_prev_diff = Output(CELL_T_M_1_GRAD)->template mutable_data<T>();
266  Output(GATES_GRAD)->ResizeLike(Input(GATES));
267  auto* X_diff = Output(GATES_GRAD)->template mutable_data<T>();
268 
269  detail::LSTMUnitGradient<T, Context>(
270  N,
271  D,
272  t,
273  C_prev,
274  X,
275  seqLengths,
276  C,
277  H,
278  C_diff,
279  H_diff,
280  drop_states_,
281  H_prev_diff,
282  C_prev_diff,
283  X_diff,
284  forget_bias_,
285  &context_);
286  return true;
287  }
288 
289  bool RunOnDevice() override {
290  return DoRunWithType<float>();
291  }
292 
293  protected:
294  INPUT_TAGS(HIDDEN_T_M_1, CELL_T_M_1, GATES, SEQ_LENGTHS);
295  // additional input tags are determined dynamically based on whether
296  // sequence_lengths is present.
297  OUTPUT_TAGS(HIDDEN_T_M_1_GRAD, CELL_T_M_1_GRAD, GATES_GRAD);
298 
299  float forget_bias_;
300  bool sequence_lengths_;
301 
302  private:
303  bool drop_states_;
304 };
305 } // namespace caffe2
306 
307 #endif // CAFFE2_OPERATORS_LSTM_UNIT_OP_H_
Workspace is a class that holds all the related objects created during runtime: (1) all blobs...
Definition: workspace.h:47
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...
Definition: blob.h:13
Definition: static.cpp:64
Definition: static.cpp:70