adjoint.cc 5.89 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 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 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
/*
 * 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.
 */

/*!
 * \file adjoint.cc
 * \brief Perform reverse-mode autodiff.
 *        Suppose we have f(x) = g(h1(x), h2(x), ..., hn(x)),
 *        df/dx = \sum_i df/dhi * dhi/dx
 *        We call df/dx as adjoint(x), df/dhi as adjoint(hi), dhi/dx is the Jacobian
 *        The idea is to first construct the reverse-dependency {input->outputs} between tensors,
 *        start from one input,
 *        (1) collect adjoints from all its dependencies (outputs),
 *        (2) multiply the Jacobian (PartialAdjoint),
 *        (3) and sum them together to get the adjoint of the input itself.
 *        The three steps are computed recursively.
 */
#include <tvm/runtime/registry.h>
#include <tvm/te/autodiff.h>
#include <tvm/tir/stmt_functor.h>
#include <topi/transform.h>
#include <topi/elemwise.h>
#include <memory>
#include <vector>

namespace tvm {
namespace te {

Tensor Identity(const Tensor& output) {
  Array<PrimExpr> shape = output->shape;
  for (auto e : output->shape) {
    // add extra dimension for Jacobian
    shape.push_back(e);
  }
  auto func =
    [&output](const Array<Var>& input_indices) {
      PrimExpr res = const_true();
      for (size_t i = 0; i < output->shape.size(); ++i) {
        res = res && (PrimExpr(input_indices[i]) ==
                      PrimExpr(input_indices[output->shape.size() + i]));
      }
      return CastNode::make(output->dtype, res);
    };
  return te::compute(shape, func, "identity");
}

Tensor VectorJacobianProduct(const Tensor &output, const Tensor &input, const Tensor &head) {
  Tensor jac = Jacobian(output, input);
  Tensor result = topi::tensordot(head, jac, /*axes=*/output->shape.size(),
                                  output->op->name + "." + input->op->name + ".grad");
  return result;
}

Array<Tensor> Gradient(const Tensor& output,
                       const Array<Tensor>& inputs,
                       const Tensor& head_or_null) {
  // Diagonal identity tensor
  Tensor head = head_or_null.get() ? head_or_null : Identity(output);

  // This Map{input -> outputs} maps a tensor to the list of tensors
  // immediately depending on it (using it in their bodies)
  std::unordered_map<Tensor, std::vector<Tensor>> reverse_dependencies;
  std::vector<Tensor> stack({output});
  while (!stack.empty()) {
    Tensor tensor = stack.back();
    stack.pop_back();
    for (const Tensor& input : tensor->op->InputTensors()) {
      if (!reverse_dependencies.count(input)) {
        stack.push_back(input);
      }
      reverse_dependencies[input].push_back(tensor);
    }
  }

  // This map maps tensors to the corresponding adjoints (dLoss/dTensor)
  std::unordered_map<Tensor, Tensor> adjoints;
  // head is the adjoint of output by definition
  adjoints[output] = head;

  // This is a recursive function that does all the work. It computes the adjoint for a given
  // tensor, adds it to the map, and returns it
  std::function<Tensor(const Tensor&)> compute_adjoint;
  compute_adjoint =
    [&compute_adjoint, &adjoints, &reverse_dependencies, &head, &output]
    (const Tensor& tensor) {
      if (!adjoints.count(tensor)) {
        // Here the adjoint hasn't been computed yet
        Tensor res_adjoint;
        std::vector<Tensor> direct_consumers = reverse_dependencies[tensor];
        if (direct_consumers.empty()) {
          // No reverse dependencies means that the output does not depend on this tensor,
          // return a zero tensor of the appropriate shape
          // (i.e., output shape + tensor shape, aka shape of Jacobian)
          Array<PrimExpr> result_shape(head->shape.begin(),
                                       head->shape.end() + (-output->shape.size()));
          for (auto e : tensor->shape) {
            result_shape.push_back(e);
          }
          res_adjoint = topi::full(result_shape, output->dtype, make_zero(output->dtype));
        } else {
          // The new adjoint is computed as a sum of the reverse dependencies' adjoints multiplied
          // by the corresponding "local" jacobians (dDep/dTensor). The computation of the jacobian
          // and the multiplication is done in the function VectorJacobianProduct
          for (const Tensor& direct_consumer : direct_consumers) {
            // part = (adjoint of direct_consumer) * Jacobian(direct_consumer, tensor)
            Tensor part = VectorJacobianProduct(
                direct_consumer, tensor, compute_adjoint(direct_consumer));
            res_adjoint = res_adjoint.get() ? topi::add(res_adjoint, part) : part;
          }
        }

        adjoints[tensor] = res_adjoint;
        return res_adjoint;
      } else {
        return adjoints[tensor];
      }
    };

  // Adjoints corresponding to inputs
  Array<Tensor> result;
  // Compute an adjoint for each input
  for (const Tensor& input : inputs) {
    result.push_back(compute_adjoint(input));
  }

  return result;
}

TVM_REGISTER_GLOBAL("te.Gradient")
.set_body([](TVMArgs args, TVMRetValue *ret) {
    LOG(WARNING) << "te.Gradient is an experimental feature.";
    if (args.size() == 2) {
      *ret = Gradient(args[0], args[1]);
    } else if (args.size() == 3) {
      *ret = Gradient(args[0], args[1], args[2]);
    }
  });

}  // namespace te
}  // namespace tvm