memory.cc 13.5 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
/*
 * 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 src/relay/op/memory/memory.cc
 * \brief Operators for manifest shape-aware memory allocation in Relay.
 */

#include <topi/elemwise.h>
#include <tvm/relay/expr.h>
#include <tvm/relay/op.h>
#include <tvm/relay/op_attr_types.h>
#include <tvm/relay/attrs/memory.h>

#include "../op_common.h"
32
#include "../../pass/infer_layout_util.h"
33 34 35 36 37 38 39 40 41 42 43
#include "../type_relations.h"

namespace tvm {
namespace relay {

TVM_REGISTER_NODE_TYPE(AllocTensorAttrs);
TVM_REGISTER_NODE_TYPE(ShapeFuncAttrs);

// The passing value in attrs and args doesn't seem super great.
// We should consider a better solution, i.e the type relation
// being able to see the arguments as well?
44
TVM_REGISTER_GLOBAL("relay.op.memory._make.alloc_storage")
45
    .set_body_typed([](Expr size, Expr alignment, DataType dtype) {
46
      auto attrs = make_object<AllocTensorAttrs>();
47 48 49 50 51 52 53 54 55 56 57
      attrs->dtype = dtype;
      static const Op& op = Op::Get("memory.alloc_storage");
      return CallNode::make(op, {size, alignment}, Attrs(attrs), {});
    });

bool AllocStorageRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
                     const TypeReporter& reporter) {
  CHECK_EQ(types.size(), 3u);
  auto size_type = types[0];
  auto tensor_type = size_type.as<TensorTypeNode>();
  CHECK(tensor_type != nullptr);
58
  CHECK_EQ(tensor_type->dtype, DataType::Int(64));
59 60 61 62
  CHECK_EQ(tensor_type->shape.size(), 0);
  auto align_type = types[1];
  auto align_ttype = align_type.as<TensorTypeNode>();
  CHECK(align_ttype != nullptr);
63
  CHECK_EQ(align_ttype->dtype, DataType::Int(64));
64 65 66 67
  CHECK_EQ(align_ttype->shape.size(), 0);
  auto mod = reporter->GetModule();
  CHECK(mod.defined());
  auto storage_name = mod->GetGlobalTypeVar("Storage");
68
  auto storage = TypeCall(storage_name, {});
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
  reporter->Assign(types[2], storage);
  return true;
}

RELAY_REGISTER_OP("memory.alloc_storage")
    .describe(R"code(Explicitly allocate storage to be used by tensors.)code" TVM_ADD_FILELINE)
    .set_num_inputs(2)
    .add_argument("size", "Tensor", "The size of the storage to allocate.")
    .add_argument("alignment", "Tensor", "The alignment of the storage.")
    .add_type_rel("AllocStorage", AllocStorageRel)
    .set_support_level(10)
    .set_attr<TOpPattern>("TOpPattern", kOpaque)
    .set_attr<TOpIsStateful>("TOpIsStateful", false)
    .set_attr<TNonComputational>("TNonComputational", true)
    .set_attr<FInferCorrectLayout>("FInferCorrectLayout", ElemwiseArbitraryLayout)
    .set_attr<FTVMCompute>("FTVMCompute",
85
                           [](const Attrs& attrs, const Array<te::Tensor>& inputs,
86
                              const Type& out_dtype) -> Array<te::Tensor> {
87 88 89
                             return {topi::identity(inputs[0])};
                           });

90
TVM_REGISTER_GLOBAL("relay.op.memory._make.alloc_tensor")
91
    .set_body_typed(
92
        [](Expr storage, tvm::relay::Expr shape, DataType dtype, Array<IndexExpr> assert_shape) {
93
          auto attrs = make_object<AllocTensorAttrs>();
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
          attrs->dtype = dtype;
          if (assert_shape.defined()) {
            attrs->assert_shape = assert_shape;
          } else {
            attrs->const_shape = Downcast<Constant>(shape);
          }
          static const Op& op = Op::Get("memory.alloc_tensor");
          return CallNode::make(op, {storage, shape}, Attrs(attrs), {});
        });

std::vector<int64_t> FromConstShape(Constant konst) {
  runtime::NDArray shape = konst->data;
  std::vector<int64_t> raw_shape;
  DLTensor tensor = shape.ToDLPack()->dl_tensor;
  CHECK_EQ(tensor.ndim, 1u);
  CHECK_EQ(tensor.dtype.code, 0U)
    << "found " << tensor.dtype.code;

  CHECK(tensor.dtype.bits == 64 || tensor.dtype.bits == 32)
    << "found " << static_cast<int>(tensor.dtype.bits);

  if (tensor.dtype.bits == 32) {
    const int32_t* int_ptr = reinterpret_cast<int32_t*>(tensor.data);
    for (auto i = 0; i < tensor.shape[0]; i++) {
      raw_shape.push_back(int_ptr[i]);
    }
  } else if (tensor.dtype.bits == 64) {
    const int64_t* int_ptr = reinterpret_cast<int64_t*>(tensor.data);
    for (auto i = 0; i < tensor.shape[0]; i++) {
      raw_shape.push_back(int_ptr[i]);
    }
  }

  return raw_shape;
}

bool AllocTensorRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
                    const TypeReporter& reporter) {
  CHECK_EQ(types.size(), 3u);
  auto alloc_attrs = attrs.as<AllocTensorAttrs>();
  CHECK(alloc_attrs != nullptr) << "must be alloc_tensor attributes";
  // First argument should be storage.
  auto mod = reporter->GetModule();
  CHECK(mod.defined());
  auto storage_name = mod->GetGlobalTypeVar("Storage");
139
  auto storage = relay::TypeCall(storage_name, {});
140 141 142 143
  reporter->Assign(types[0], storage);
  // Second argument should be shape tensor.
  auto tt = types[1].as<TensorTypeNode>();
  CHECK(tt != nullptr) << "must be tensor type";
144
  auto rank = tt->shape[0].as<tvm::IntImmNode>();
145 146 147 148 149 150 151 152 153 154 155 156
  CHECK(rank != nullptr);
  auto dims = rank->value;

  // Constant node case.
  Type alloc_type;
  if (alloc_attrs->const_shape.defined()) {
    auto con = alloc_attrs->const_shape;
    auto sh = FromConstShape(con);
    Array<IndexExpr> out_shape;
    for (auto i = 0u; i < dims; i++) {
      out_shape.push_back(tvm::Integer(sh[i]));
    }
157
    alloc_type = TensorType(out_shape, alloc_attrs->dtype);
158 159 160
  } else {
    CHECK(alloc_attrs->assert_shape.defined())
        << "the assert_shape must be set when const_shape is not";
161
    alloc_type = TensorType(alloc_attrs->assert_shape, alloc_attrs->dtype);
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    return true;
  }

  reporter->Assign(types[2], alloc_type);
  return true;
}

RELAY_REGISTER_OP("memory.alloc_tensor")
    .describe(R"code(Explicitly allocate storage to be used by tensors.)code" TVM_ADD_FILELINE)
    .set_num_inputs(2)
    .add_argument("storage", "Storage", "The storage to allocate from.")
    .add_argument("shape", "Tensor", "The shape of the tensor to allocate.")
    .add_type_rel("AllocTensor", AllocTensorRel)
    .set_support_level(10)
    .set_attr<TOpPattern>("TOpPattern", kOpaque)
    .set_attr<TOpIsStateful>("TOpIsStateful", false)
    .set_attr<TNonComputational>("TNonComputational", true)
    .set_attr<FInferCorrectLayout>("FInferCorrectLayout", ElemwiseArbitraryLayout)
    .set_attr<FTVMCompute>("FTVMCompute",
181
                           [](const Attrs& attrs, const Array<te::Tensor>& inputs,
182
                              const Type& out_dtype) -> Array<te::Tensor> {
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
                             return {topi::identity(inputs[0])};
                           });

bool InvokeTVMOPRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
                    const TypeReporter& reporter) {
  CHECK_EQ(types.size(), 4u);
  auto func_type = types[0].as<FuncTypeNode>();
  CHECK(func_type != nullptr) << "input must be operator with known type";
  auto input_type = types[1].as<TupleTypeNode>();
  auto output_type = types[2].as<TupleTypeNode>();
  CHECK(input_type != nullptr)
      << "internal invariant violated: invoke_tvm_op inputs must be a tuple";
  CHECK(output_type != nullptr)
      << "internal invariant violated: invoke_tvm_op outputs must be a tuple";
  Type ex_output;
  if (func_type->ret_type.as<TensorTypeNode>()) {
199
    ex_output = TupleType({func_type->ret_type});
200 201 202 203
  } else {
    CHECK(func_type->ret_type.as<TupleTypeNode>()) << "should be tuple type";
    ex_output = func_type->ret_type;
  }
204
  auto ex_input = TupleType(func_type->arg_types);
205 206
  reporter->Assign(ex_input, GetRef<Type>(input_type));
  reporter->Assign(ex_output, GetRef<Type>(output_type));
207
  reporter->Assign(types[3], TupleType::Empty());
208 209 210
  return true;
}

211
TVM_REGISTER_GLOBAL("relay.op.memory._make.invoke_tvm_op")
212
    .set_body_typed(
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
        [](Expr func, Expr inputs, Expr outputs) {
          return CallNode::make(Op::Get("memory.invoke_tvm_op"), {func, inputs, outputs}, Attrs());
        });

RELAY_REGISTER_OP("memory.invoke_tvm_op")
    .describe(R"code(Invoke an operation compiled by TVM.)code" TVM_ADD_FILELINE)
    .set_num_inputs(3)
    .add_argument("op", "Function", "The operation to call")
    .add_argument("ins", "Tuple", "The input tensors.")
    .add_argument("outs", "Tuple", "The output tensors.")
    .add_type_rel("InvokeTVMOP", InvokeTVMOPRel)
    .set_support_level(10)
    .set_attr<TOpPattern>("TOpPattern", kOpaque)
    .set_attr<TOpIsStateful>("TOpIsStateful", false)
    .set_attr<TNonComputational>("TNonComputational", true)
    .set_attr<FInferCorrectLayout>("FInferCorrectLayout", ElemwiseArbitraryLayout)
    .set_attr<FTVMCompute>("FTVMCompute",
230
                           [](const Attrs& attrs, const Array<te::Tensor>& inputs,
231
                              const Type& out_dtype) -> Array<te::Tensor> {
232 233 234 235 236 237 238
                             return {topi::identity(inputs[0])};
                           });

bool KillRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
             const TypeReporter& reporter) {
  CHECK_EQ(types.size(), 2u);
  // TODO(@jroesch): should only support tensors.
239
  reporter->Assign(types[1], TupleType::Empty());
240 241 242 243 244 245 246 247 248 249 250 251 252 253
  return true;
}

RELAY_REGISTER_OP("memory.kill")
    .describe(R"code(Mark a tensor for release to the allocator.)code" TVM_ADD_FILELINE)
    .set_num_inputs(3)
    .add_argument("to_free", "Tensor", "The tensor to free.")
    .add_type_rel("Kill", KillRel)
    .set_support_level(10)
    .set_attr<TOpPattern>("TOpPattern", kOpaque)
    .set_attr<TOpIsStateful>("TOpIsStateful", false)
    .set_attr<TNonComputational>("TNonComputational", true)
    .set_attr<FInferCorrectLayout>("FInferCorrectLayout", ElemwiseArbitraryLayout)
    .set_attr<FTVMCompute>("FTVMCompute",
254
                           [](const Attrs& attrs, const Array<te::Tensor>& inputs,
255
                              const Type& out_dtype) -> Array<te::Tensor> {
256 257 258
                             return {topi::identity(inputs[0])};
                           });

259
TVM_REGISTER_GLOBAL("relay.op.memory._make.shape_func")
260
    .set_body_typed(
261 262
      [](Expr func, Expr inputs, Expr outputs, Array<tvm::Integer> is_input) {
      static const Op& op = Op::Get("memory.shape_func");
263
      auto attrs = make_object<ShapeFuncAttrs>();
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
      attrs->is_input = is_input;
      return CallNode::make(op, {func, inputs, outputs}, Attrs(attrs), {});
    });

static void FlattenTypeAux(const Type& type, std::vector<TensorType>* out) {
  if (auto tt = type.as<TensorTypeNode>()) {
    out->push_back(GetRef<TensorType>(tt));
  } else if (auto tuple_ty = type.as<TupleTypeNode>()) {
    for (auto field : tuple_ty->fields) {
      FlattenTypeAux(field, out);
    }
  } else {
    LOG(FATAL) << "unsupported " << type;
  }
}

std::vector<TensorType> FlattenType(const Type& type) {
  std::vector<TensorType> out;
  FlattenTypeAux(type, &out);
  return out;
}

Expr PackByType(const Type& t, const Array<Expr>& exprs) {
  LOG(FATAL) << "NYI";
  return Expr();
}

bool ShapeFuncRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
                  const TypeReporter& reporter) {
  CHECK_EQ(types.size(), 4u);
  auto shape_func_attrs = attrs.as<ShapeFuncAttrs>();
  CHECK(shape_func_attrs != nullptr) << "Internal compiler error";

  auto func_type = types[0].as<FuncTypeNode>();
  CHECK(func_type != nullptr);

300
  auto tuple = TupleType(func_type->arg_types);
301 302 303 304 305 306 307 308 309 310 311
  auto in_types = FlattenType(tuple);
  auto out_types = FlattenType(func_type->ret_type);

  Array<Type> shape_func_ins, shape_func_outs;
  for (size_t i = 0; i < in_types.size(); i++) {
    auto in_type = in_types[i];

    if (shape_func_attrs->is_input[i]) {
      shape_func_ins.push_back(in_type);
    } else {
      auto shape = RankShape(in_type->shape);
312
      shape_func_ins.push_back(TensorType(shape, DataType::Int(64)));
313 314 315 316 317
    }
  }

  for (auto out_type : out_types) {
    auto rank_shape = RankShape(out_type->shape);
318
    shape_func_outs.push_back(TensorType(rank_shape, DataType::Int(64)));
319 320
  }

321 322
  auto input_type = TupleType(shape_func_ins);
  auto output_type = TupleType(shape_func_outs);
323 324 325

  reporter->Assign(types[1], input_type);
  reporter->Assign(types[2], output_type);
326
  reporter->Assign(types[3], TupleType::Empty());
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341

  return true;
}

RELAY_REGISTER_OP("memory.shape_func")
    .describe(R"code(Get the shape of a tensor.)code" TVM_ADD_FILELINE)
    .set_num_inputs(3)
    .add_argument("tensor", "Tensor", "The tensor to retrieve the shape for.")
    .add_type_rel("ShapeFuncRel", ShapeFuncRel)
    .set_support_level(10)
    .set_attr<TOpPattern>("TOpPattern", kOpaque)
    .set_attr<TOpIsStateful>("TOpIsStateful", false)
    .set_attr<TNonComputational>("TNonComputational", true)
    .set_attr<FInferCorrectLayout>("FInferCorrectLayout", ElemwiseArbitraryLayout)
    .set_attr<FTVMCompute>("FTVMCompute",
342
                           [](const Attrs& attrs, const Array<te::Tensor>& inputs,
343
                              const Type& out_dtype) -> Array<te::Tensor> {
344 345 346 347 348
                             return {topi::identity(inputs[0])};
                           });

}  // namespace relay
}  // namespace tvm