mxnet
imperative.h
Go to the documentation of this file.
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
20 #ifndef MXNET_IMPERATIVE_H_
21 #define MXNET_IMPERATIVE_H_
22 
23 #include <mxnet/op_attr_types.h>
24 #include <mxnet/graph_attr_types.h>
25 #include <mxnet/c_api.h>
26 #include <nnvm/symbolic.h>
27 #include <nnvm/op.h>
28 #include <nnvm/graph.h>
29 #include <vector>
30 #include <atomic>
31 #include <utility>
32 #include <string>
33 #include <unordered_map>
34 
35 #include "./ndarray.h"
36 
37 namespace mxnet {
50 class Imperative {
51  public:
53  class AGInfo {
54  public:
58  std::vector<NDArray> outputs;
59  std::vector<NDArray> out_grads;
61 
62  AGInfo() :
63  grad_req(kNullOp), fresh_out_grad(false) {}
64 
65  static void Clear(const nnvm::NodePtr& node) {
66  if (node == nullptr || node->info.empty()) return;
67  AGInfo& info = Get(node);
68  if (info.grad_req != kNullOp) return;
69  node->info.clear();
70  }
71 
72  static AGInfo& Get(const nnvm::NodePtr& node) {
73  return dmlc::get<AGInfo>(node->info);
74  }
75 
76  static AGInfo& Create(const nnvm::NodePtr& node) {
77  node->info.construct<AGInfo>();
78  return Get(node);
79  }
80 
81  static bool IsNone(const NDArray& arr) {
82  return arr.entry_.node == nullptr || arr.entry_.node->info.empty();
83  }
84 
85  static bool IsVariable(const nnvm::NodePtr& node) {
86  AGInfo& info = Get(node);
87  return info.grad_req != kNullOp && info.outputs.size() == 1
88  && info.out_grads.size() == 1;
89  }
90  };
92  bool is_training() const {
93  return is_train_;
94  }
96  bool set_is_training(bool is_train) {
97  bool old = is_train_;
98  is_train_ = is_train;
99  return old;
100  }
102  bool is_recording() const {
103  return is_recording_;
104  }
107  bool old = is_recording_;
108  is_recording_ = is_recording;
109  return old;
110  }
114  int is_np_shape() const {
115  if (is_np_shape_global_) {
116  return 2;
117  }
118  return is_np_shape_thread_local_ ? 1 : 0;
119  }
122  NumpyShape flag = static_cast<NumpyShape>(is_np_shape);
123  bool old = this->is_np_shape();
124  switch (flag) {
125  case GlobalOn:
126  is_np_shape_global_ = true;
127  is_np_shape_thread_local_ = true;
128  break;
129  case ThreadLocalOn:
130  is_np_shape_thread_local_ = true;
131  break;
132  case Off:
133  is_np_shape_global_ = false;
134  is_np_shape_thread_local_ = false;
135  break;
136  }
137  return old;
138  }
140  void RecordOp(nnvm::NodeAttrs&& attrs,
141  const std::vector<NDArray*>& inputs,
142  const std::vector<NDArray*>& outputs,
143  const OpStatePtr& state = OpStatePtr(),
144  std::vector<bool>* p_save_inputs = nullptr,
145  std::vector<bool>* p_save_outputs = nullptr);
147  OpStatePtr Invoke(const Context& default_ctx,
148  const nnvm::NodeAttrs& attrs,
149  const std::vector<NDArray*>& inputs,
150  const std::vector<NDArray*>& outputs);
153  const nnvm::NodeAttrs& attrs,
154  const std::vector<NDArray*>& inputs,
155  const std::vector<NDArray*>& outputs,
156  const std::vector<OpReqType>& req,
157  const DispatchMode dispatch_mode,
160  void MarkVariables(const std::vector<NDArray*>& variables,
161  const std::vector<uint32_t>& grad_reqs,
162  const std::vector<NDArray*>& gradients);
164  std::vector<NDArray*> Backward(const std::vector<NDArray*>& outputs,
165  const std::vector<NDArray*>& ograds,
166  const std::vector<NDArray*>& variables,
167  bool is_train, bool retain_graph,
168  bool create_graph);
170  static Imperative* Get();
172  static bool PreferBulkExecInference() {
173  return dmlc::GetEnv("MXNET_EXEC_BULK_EXEC_INFERENCE", true);
174  }
176  static bool PreferBulkExecTrain() {
177  return dmlc::GetEnv("MXNET_EXEC_BULK_EXEC_TRAIN", true);
178  }
180  static int BulkExecMaxNodeTrainFwd() {
181  return dmlc::GetEnv("MXNET_EXEC_BULK_EXEC_MAX_NODE_TRAIN_FWD",
182  dmlc::GetEnv("MXNET_EXEC_BULK_EXEC_MAX_NODE_TRAIN", 15));
183  }
185  static int BulkExecMaxNodeTrainBwd() {
186  return dmlc::GetEnv("MXNET_EXEC_BULK_EXEC_MAX_NODE_TRAIN_BWD",
187  dmlc::GetEnv("MXNET_EXEC_BULK_EXEC_MAX_NODE_TRAIN", 15));
188  }
189 
190  private:
191  friend class NDArray;
193  Imperative() {
194  if (PreferBulkExecTrain())
195  backward_bulk_size_ = BulkExecMaxNodeTrainBwd();
196  }
198  void GetBackwardDependency(
199  const nnvm::NodePtr& node,
200  uint32_t num_inputs, uint32_t num_outputs,
201  std::vector<bool> *p_save_inputs,
202  std::vector<bool> *p_save_outputs);
204 #if DMLC_CXX11_THREAD_LOCAL
205  static thread_local bool is_train_;
206  static thread_local bool is_recording_;
207  // TOOD(junwu): Added numpy compatibility switch for backward compatibility.
208  // Delete it in the next major release.
209  static thread_local bool is_np_shape_thread_local_;
210 #else
211  static MX_THREAD_LOCAL bool is_train_;
212  static MX_THREAD_LOCAL bool is_recording_;
213  // TOOD(junwu): Added numpy compatibility switch for backward compatibility.
214  // Delete it in the next major release.
215  static MX_THREAD_LOCAL bool is_np_shape_thread_local_;
216 #endif
217  bool is_np_shape_global_{false};
219  std::atomic<uint64_t> node_count_{0};
221  std::atomic<uint64_t> variable_count_{0};
223  int backward_bulk_size_{0};
224 };
225 
226 } // namespace mxnet
227 #endif // MXNET_IMPERATIVE_H_
Definition: imperative.h:48
bool is_recording() const
whether operator recording is on.
Definition: imperative.h:102
static bool IsNone(const NDArray &arr)
Definition: imperative.h:81
static int BulkExecMaxNodeTrainFwd()
The max number of op nodes in a bulk during forward pass of training.
Definition: imperative.h:180
static AGInfo & Create(const nnvm::NodePtr &node)
Definition: imperative.h:76
Definition: imperative.h:48
bool is_training() const
whether operator recording is on.
Definition: imperative.h:92
no operation, do not write anything
Definition: op_attr_types.h:47
bool set_is_training(bool is_train)
turn on or turn off operator recording for autograd.
Definition: imperative.h:96
The attributes of the current operation node. Usually are additional parameters like axis...
Definition: node.h:120
namespace of mxnet
Definition: base.h:89
std::vector< NDArray * > Backward(const std::vector< NDArray * > &outputs, const std::vector< NDArray * > &ograds, const std::vector< NDArray * > &variables, bool is_train, bool retain_graph, bool create_graph)
compute the gradient of outputs w.r.t variables.
static void Clear(const nnvm::NodePtr &node)
Definition: imperative.h:65
OpStatePtr Invoke(const Context &default_ctx, const nnvm::NodeAttrs &attrs, const std::vector< NDArray * > &inputs, const std::vector< NDArray * > &outputs)
std::shared_ptr< Node > NodePtr
we always used NodePtr for a reference pointer to the node, so this alias can be changed in case...
Definition: node.h:49
AGInfo()
Definition: imperative.h:62
DispatchMode
the dispatch mode of the operator
Definition: op_attr_types.h:122
NodePtr node
the source node of this data
Definition: node.h:76
std::vector< NDArray > outputs
Definition: imperative.h:58
int is_np_shape() const
return current numpy compatibility status, GlobalOn(2), ThreadLocalOn(1), Off(0). ...
Definition: imperative.h:114
Definition: imperative.h:53
bool set_is_recording(bool is_recording)
turn on or turn off operator recording for autograd.
Definition: imperative.h:106
bool fresh_out_grad
Definition: imperative.h:60
OpStatePtr state
Definition: imperative.h:57
std::vector< NDArray > out_grads
Definition: imperative.h:59
void RecordOp(nnvm::NodeAttrs &&attrs, const std::vector< NDArray * > &inputs, const std::vector< NDArray * > &outputs, const OpStatePtr &state=OpStatePtr(), std::vector< bool > *p_save_inputs=nullptr, std::vector< bool > *p_save_outputs=nullptr)
to record operator, return corresponding node.
OpReqType grad_req
Definition: imperative.h:56
Context ctx
Definition: imperative.h:55
Configuation of nnvm as well as basic data structure.
OpReqType
operation request type to Forward and Backward
Definition: op_attr_types.h:45
OpStatePtr InvokeOp(const Context &ctx, const nnvm::NodeAttrs &attrs, const std::vector< NDArray * > &inputs, const std::vector< NDArray * > &outputs, const std::vector< OpReqType > &req, const DispatchMode dispatch_mode, OpStatePtr state=OpStatePtr())
static bool IsVariable(const nnvm::NodePtr &node)
Definition: imperative.h:85
runtime functions for NDArray
Definition: imperative.h:50
Definition: imperative.h:48
static AGInfo & Get(const nnvm::NodePtr &node)
Definition: imperative.h:72
Operator information structor.
static bool PreferBulkExecTrain()
Should op execution bulking be employed during training.
Definition: imperative.h:176
Symbolic graph construction API.
static int BulkExecMaxNodeTrainBwd()
The max number of op nodes in a bulk during backward pass of training.
Definition: imperative.h:185
bool set_is_np_shape(int is_np_shape)
specify numpy compatibility off, thread local on or global on.
Definition: imperative.h:121
static bool PreferBulkExecInference()
Should op execution bulking be employed during inference.
Definition: imperative.h:172
void MarkVariables(const std::vector< NDArray * > &variables, const std::vector< uint32_t > &grad_reqs, const std::vector< NDArray * > &gradients)
mark variables for computing gradients.
Context information about the execution environment.
Definition: base.h:102
ndarray interface
Definition: ndarray.h:82
NumpyShape
there are three numpy shape flags based on priority. GlobalOn turn on numpy shape flag globally...
Definition: imperative.h:48
Operator state. This is a pointer type, its content is mutable even if OpStatePtr is const...
Definition: op_attr_types.h:148