eric-haibin-lin commented on a change in pull request #7698: Second order 
gradient and Subgraph execution
URL: https://github.com/apache/incubator-mxnet/pull/7698#discussion_r140639796
 
 

 ##########
 File path: src/imperative/cached_op.cc
 ##########
 @@ -0,0 +1,463 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+#include <unordered_set>
+#include <iostream>
+#include "./imperative_utils.h"
+
+namespace mxnet {
+
+Imperative::CachedOp::CachedOp(const nnvm::Symbol& sym) {
+  using namespace nnvm;
+  using namespace imperative;
+  static const std::vector<const Op*> zero_ops{Op::Get("zeros_like"), 
Op::Get("_zeros")};
+  static const auto _copy = Op::Get("_copy");
+
+  // construct forward graph
+  {
+    NodeEntryMap<int> dedup_out;
+    for (const auto& i : sym.outputs) {
+      if (dedup_out.count(i)) {
+        NodePtr copy_node = Node::Create();
+        copy_node->attrs.op = _copy;
+        copy_node->attrs.name =
+            i.node->attrs.name + "_copy" + std::to_string(dedup_out[i]++);
+        copy_node->inputs.emplace_back(i);
+        if (_copy->attr_parser != nullptr) {
+          _copy->attr_parser(&(copy_node->attrs));
+        }
+        fwd_graph_.outputs.push_back(NodeEntry{copy_node, 0, 0});
+      } else {
+        dedup_out.insert({i, 0});
+        fwd_graph_.outputs.push_back(i);
+      }
+    }
+    const auto& idx = fwd_graph_.indexed_graph();
+    CHECK_GE(idx.input_nodes().size(), 1) << "CachedOp requires at least 1 
input";
+
+    std::vector<uint32_t> ref_count(idx.num_node_entries(), 0);
+    for (const auto& i : idx.input_nodes()) ++ref_count[idx.entry_id(i, 0)];
+    for (const auto& i : idx.outputs()) ++ref_count[idx.entry_id(i)];
+    for (size_t i = 0; i < idx.num_nodes(); ++i) {
+      for (const auto& j : idx[i].inputs) ++ref_count[idx.entry_id(j)];
+    }
+
+    fwd_graph_.attrs["forward_ref_count"] =
+        std::make_shared<dmlc::any>(std::move(ref_count));
+  }
+
+  // construct backward graph
+  std::vector<NodeEntry> ograd_entries;
+  {
+    ograd_entries.reserve(fwd_graph_.outputs.size());
+    for (size_t i = 0; i < fwd_graph_.outputs.size(); ++i) {
+      ograd_entries.emplace_back(NodeEntry{Node::Create(), 0, 0});
+    }
+
+    std::vector<NodeEntry> xs;
+    std::vector<NodePtr> args = sym.ListInputs(Symbol::kReadOnlyArgs);
+    xs.reserve(args.size());
+    for (const auto& i : args) xs.emplace_back(NodeEntry{i, 0, 0});
+    CHECK_GT(xs.size(), 0)
+        << "There are no inputs in computation graph that require gradients.";
+
+    grad_graph_ = pass::Gradient(
+        fwd_graph_, fwd_graph_.outputs, xs, ograd_entries,
+        exec::AggregateGradient, nullptr, nullptr,
+        zero_ops, "_copy");
+  }
+
+  // construct full graph
+  {
+    size_t num_forward_nodes = fwd_graph_.indexed_graph().num_nodes();
+    size_t num_forward_entries = fwd_graph_.indexed_graph().num_node_entries();
+
+    full_graph_.outputs = fwd_graph_.outputs;
+    curr_grad_req_ = std::vector<bool>(grad_graph_.outputs.size(), true);
+    for (const auto& i : grad_graph_.outputs) 
full_graph_.outputs.emplace_back(i);
+    const auto& idx = full_graph_.indexed_graph();
+
+    std::vector<uint32_t> ref_count(idx.num_node_entries(), 0);
+    for (size_t i = num_forward_nodes; i < idx.num_nodes(); ++i) {
+      for (const auto& j : idx[i].inputs) {
+         ++ref_count[idx.entry_id(j)];
+      }
+    }
+
+    auto full_ref_count = fwd_graph_.GetAttr<std::vector<uint32_t> 
>("forward_ref_count");
+    for (size_t i = 0; i < num_forward_entries; ++i) full_ref_count[i] += 
ref_count[i];
+    fwd_graph_.attrs["full_ref_count"] =
+        std::make_shared<dmlc::any>(std::move(full_ref_count));
+
+    size_t num_forward_inputs = num_inputs();
+    for (uint32_t i = 0; i < ograd_entries.size(); ++i) {
+      if (!idx.exist(ograd_entries[i].node.get())) continue;
+      auto eid = idx.entry_id(ograd_entries[i]);
+      if (ref_count[eid] > 0) {
+        bwd_ograd_dep_.push_back(i);
+        bwd_input_eid_.push_back(eid);
+      }
+    }
+    save_inputs_.resize(num_forward_inputs, false);
+    for (uint32_t i = 0; i < num_forward_inputs; ++i) {
+      auto eid = idx.entry_id(idx.input_nodes()[i], 0);
+      if (ref_count[eid] > 0) {
+        save_inputs_[i] = true;
+        bwd_in_dep_.push_back(i);
+        bwd_input_eid_.push_back(eid);
+      }
+    }
+    save_outputs_.resize(idx.outputs().size(), false);
+    for (uint32_t i = 0; i < idx.outputs().size(); ++i) {
+      auto eid = idx.entry_id(idx.outputs()[i]);
+      if (ref_count[eid] > 0) {
+        save_outputs_[i] = true;
+        bwd_out_dep_.push_back(i);
+        bwd_input_eid_.push_back(eid);
+      }
+    }
+  }
+}
+
+std::vector<nnvm::NodeEntry> Imperative::CachedOp::Gradient(
+    const nnvm::NodePtr& node,
+    const std::vector<nnvm::NodeEntry>& ograds) {
+  using namespace nnvm;
+  static const auto _backward_CachedOp = Op::Get("_backward_CachedOp");
+  static const auto _CachedOp_NoGrad = Op::Get("_CachedOp_NoGrad");
+
+  auto p = Node::Create();
+  p->attrs.op = _backward_CachedOp;
+  p->attrs.name = node->attrs.name + "_backward";
+  p->attrs.parsed = node->attrs.parsed;
+  p->control_deps.push_back(node);
+  p->inputs.reserve(bwd_ograd_dep_.size() + bwd_in_dep_.size() + 
bwd_out_dep_.size());
+  for (auto i : bwd_ograd_dep_) p->inputs.push_back(ograds[i]);
+  for (auto i : bwd_in_dep_) p->inputs.push_back(node->inputs[i]);
+  for (auto i : bwd_out_dep_) p->inputs.emplace_back(NodeEntry{node, i, 0});
+  std::vector<NodeEntry> ret;
+  ret.reserve(num_inputs());
+  const auto& auxs = mutable_input_nodes();
+  if (auxs.size()) {
+    auto nop = Node::Create();
+    nop->attrs.op = _CachedOp_NoGrad;
+    nop->attrs.parsed = static_cast<uint32_t>(auxs.size());
+    nop->control_deps.push_back(node);
+    uint32_t j = 0, k = 0;
+    for (const auto& i : fwd_graph_.indexed_graph().input_nodes()) {
+      if (auxs.count(i)) {
+        ret.emplace_back(NodeEntry{nop, j++, 0});
+      } else {
+        ret.emplace_back(NodeEntry{p, k++, 0});
+      }
+    }
+  } else {
+    for (uint32_t i = 0; i < num_inputs(); ++i) ret.emplace_back(NodeEntry{p, 
i, 0});
+  }
+  return ret;
+}
+
+nnvm::Graph Imperative::CachedOp::GetForwardGraph(
+    const bool recording, const std::vector<NDArray*>& inputs) {
+  using namespace nnvm;
+  using namespace imperative;
+  std::lock_guard<std::mutex> lock(mutex_);
+  CHECK_EQ(inputs.size(), num_inputs());
+  nnvm::Graph& g = fwd_graph_;
+
+  ShapeVector shape_inputs;
+  DTypeVector dtype_inputs;
+  StorageTypeVector storage_type_inputs;
+  shape_inputs.reserve(inputs.size());
+  dtype_inputs.reserve(inputs.size());
+  storage_type_inputs.reserve(inputs.size());
+  for (uint32_t i = 0; i < inputs.size(); ++i) {
+    shape_inputs.emplace_back(inputs[i]->shape());
+    dtype_inputs.emplace_back(inputs[i]->dtype());
+    storage_type_inputs.emplace_back(inputs[i]->storage_type());
+  }
+
+  bool match = true;
+  match &= CheckAndInferShape(&g, std::move(shape_inputs), true);
+  match &= CheckAndInferType(&g, std::move(dtype_inputs), true);
+  match &= CheckAndInferStorageType(&g, inputs[0]->ctx(),
+                                    std::move(storage_type_inputs), true);
+
+  if (!match) {
+    g.attrs.erase("forward_mem_plan");
+    g.attrs.erase("full_mem_plan");
+  } else if (g.attrs.count(recording ? "full_mem_plan" : "forward_mem_plan")) {
+    return g;
+  }
+
+  const auto& idx = g.indexed_graph();
+
+  StorageVector storage(idx.num_node_entries(), exec::kBadStorageID);
+  for (const auto i : idx.input_nodes()) storage[idx.entry_id(i, 0)] = 
exec::kExternalStorageID;
+
+  auto mem_plan = PlanMemory(
+      &g, std::move(storage), g.GetAttr<std::vector<uint32_t> >(
+          recording ? "full_ref_count" : "forward_ref_count"));
+  g.attrs[recording ? "full_mem_plan" : "forward_mem_plan"] =
+      std::make_shared<dmlc::any>(std::move(mem_plan));
+
+  return g;
+}
+
+nnvm::Graph Imperative::CachedOp::GetBackwardGraph(
+    const OpStatePtr& op_state,
+    const std::vector<OpReqType>& reqs,
+    const std::vector<NDArray*>& inputs) {
+  using namespace nnvm;
+  using namespace imperative;
+  std::lock_guard<std::mutex> lock(mutex_);
+  nnvm::Graph& g = full_graph_;
+  auto& state = op_state.get_state<CachedOpState>();
+  bool req_match = true;
+  for (size_t i = 0; i < reqs.size(); ++i) {
+    if (curr_grad_req_[i] != (reqs[i] != kNullOp)) {
+      curr_grad_req_[i] = reqs[i] != kNullOp;
+      req_match = false;
+    }
+  }
+  if (!req_match) {
+    g = nnvm::Graph();
+    g.outputs = fwd_graph_.outputs;
+    for (size_t i = 0; i < grad_graph_.outputs.size(); ++i) {
+      if (curr_grad_req_[i]) g.outputs.emplace_back(grad_graph_.outputs[i]);
+    }
+  }
+
+  const auto& idx = g.indexed_graph();
+  size_t num_forward_nodes = fwd_graph_.indexed_graph().num_nodes();
+  size_t num_forward_entries = fwd_graph_.indexed_graph().num_node_entries();
 
 Review comment:
   Is `num_forward_nodes` and `num_forward_entries ` from fwd_graph correct? 
The cached op takes the output of other ops and treats it as its input, which 
is not part of the fwd_graph inputs.
 
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

Reply via email to