tvm
instance_norm.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 
24 #ifndef TVM_TOPI_NN_INSTANCE_NORM_H_
25 #define TVM_TOPI_NN_INSTANCE_NORM_H_
26 
27 #include <tvm/te/operation.h>
28 #include <tvm/topi/tags.h>
29 
30 #include <string>
31 
32 namespace tvm {
33 namespace topi {
34 namespace nn {
35 
36 using namespace tvm::te;
37 
53 inline Tensor instance_norm(const Tensor& data, const Tensor& gamma, const Tensor& beta,
54  int channel_axis, const ffi::Array<int64_t>& axis, double epsilon,
55  std::string name = "T_instance_norm", std::string tag = kInjective) {
56  const auto& data_type = data->dtype;
57  const auto& gamma_type = gamma.defined() ? gamma->dtype : data_type;
58  const auto& beta_type = beta.defined() ? beta->dtype : data_type;
59  TVM_FFI_ICHECK(data_type == gamma_type && data_type == beta_type)
60  << "instance_norm: data, gamma and beta must have the same type";
61  TVM_FFI_ICHECK(data_type == PrimType::Float(32) || data_type == PrimType::Float(16))
62  << "instance_norm: only support float32 and float16 for now";
63  bool is_float16 = data_type == PrimType::Float(16);
64  // sum x and x^2
65  auto ndim = data->shape.size();
66  TVM_FFI_ICHECK_NE(ndim, 0) << "Cannot reduce a 0 dim Tensor";
67  auto real_axis = GetRealAxis(static_cast<int>(ndim), axis);
68  auto reduce_axes = MakeReduceAxes(real_axis, data);
69  auto target_shape =
70  MakeReduceTargetShape(real_axis, data, /*keepdims=*/false, /*atleast1d=*/true);
71  auto func = MakeTupleSumReducer();
72  PrimType f32_ty = PrimType::Float(32);
73 
74  auto compute = [ndim, is_float16, &real_axis, &reduce_axes, &func, &data,
75  f32_ty](const ffi::Array<PrimVar>& indices) {
76  ffi::Array<PrimExpr> eval_range;
77  int arg_counter = 0;
78  int red_counter = 0;
79 
80  for (size_t i = 0; i < ndim; ++i) {
81  if (std::find(real_axis.begin(), real_axis.end(), i) != real_axis.end()) {
82  // real_axis contains i
83  eval_range.push_back(reduce_axes[red_counter]);
84  red_counter++;
85  } else {
86  eval_range.push_back(indices[arg_counter]);
87  arg_counter++;
88  }
89  }
90  auto square = [is_float16, f32_ty](const PrimExpr& x) {
91  if (is_float16) {
92  return Cast(f32_ty, x) * Cast(f32_ty, x);
93  }
94  return x * x;
95  };
96  if (is_float16) {
97  return func({Cast(f32_ty, data(eval_range)), square(data(eval_range))}, reduce_axes, nullptr);
98  } else {
99  return func({data(eval_range), square(data(eval_range))}, reduce_axes, nullptr);
100  }
101  };
102 
103  auto temp_x_x2 =
104  tvm::te::compute(target_shape, compute, data->op->name + "_red_temp", kCommReduce);
105 
106  auto temp_x = temp_x_x2[0];
107  auto temp_x2 = temp_x_x2[1];
108 
109  auto reduce_extent = MakeConst(PrimType(data->dtype), 1);
110  for (int i : real_axis) {
111  reduce_extent *= data->shape[i];
112  }
113  auto instance_norm_func = [&](const ffi::Array<PrimVar>& indices) {
114  ffi::Array<PrimVar> reduce_indices, non_reduce_indices;
115 
116  for (int i = 0, n = static_cast<int>(indices.size()); i < n; ++i) {
117  if (std::find(real_axis.begin(), real_axis.end(), i) != real_axis.end()) {
118  reduce_indices.push_back(indices[i]);
119  } else {
120  non_reduce_indices.push_back(indices[i]);
121  }
122  }
123  PrimVar channel;
124  channel = indices[channel_axis];
125  auto mean = temp_x(non_reduce_indices) / reduce_extent;
126  auto var = temp_x2(non_reduce_indices) / reduce_extent - mean * mean;
127  auto instance_norm = (data(indices) - mean) * tvm::rsqrt(var + MakeConst(var.ty(), epsilon));
128  if (is_float16) {
130  }
131  instance_norm = topi::multiply(instance_norm, gamma(channel));
132  if (beta.defined()) {
133  instance_norm = topi::add(instance_norm, beta(channel));
134  }
135  return instance_norm;
136  };
137  return tvm::te::compute(data->shape, instance_norm_func, name, tag);
138 }
139 
140 } // namespace nn
141 } // namespace topi
142 } // namespace tvm
143 
144 #endif // TVM_TOPI_NN_INSTANCE_NORM_H_
Typed reference/view over any Expr whose ExprNode::ty is PrimType.
Definition: base_expr.h:354
Definition: base_expr.h:113
static PrimType Float(int bits, int lanes=1)
Construct a floating-point type with fixed lanes.
ExpectedType ty() const
Definition: base_expr.h:333
Tensor structure representing a possible input, or intermediate computation result.
Definition: tensor.h:100
Managed reference to CastNode.
Definition: expr.h:96
Checked scalar view over a VarNode.
Definition: var.h:127
Tensor expression language DSL.
Definition: extracted_task.h:32
PrimVar var(std::string name_hint, PrimType t=PrimType::Int(32))
Construct a new Var expression.
Tensor compute(ffi::Array< PrimExpr > shape, FCompute fcompute, std::string name="tensor", std::string tag="", ffi::Map< ffi::String, ffi::Any > attrs={})
Construct a new tensor by computing over shape, using the computation rule: result_tensor[axis] = fco...
PrimExpr MakeConst(PrimType dtype, ValueType value, Span span=Span())
Make a const value with certain data type.
Definition: op.h:1012
Tensor instance_norm(const Tensor &data, const Tensor &gamma, const Tensor &beta, int channel_axis, const ffi::Array< int64_t > &axis, double epsilon, std::string name="T_instance_norm", std::string tag=kInjective)
Instance normalization.
Definition: instance_norm.h:53
FCommReduce MakeTupleSumReducer()
Create communitive reducer summing over tuples.
Definition: reduction.h:601
ffi::Array< PrimExpr > MakeReduceTargetShape(const std::vector< int > &real_axis, const Tensor &data, bool keepdims, bool atleast1d)
Calculate the target shape for a reduce op.
Definition: reduction.h:99
constexpr auto kInjective
Definition: tags.h:33
ffi::Array< IterVar > MakeReduceAxes(const std::vector< int > &real_axis, const Tensor &data)
Enumerate the axes for a reduce op.
Definition: reduction.h:89
tvm::PrimExpr multiply(const tvm::PrimExpr &a, const tvm::PrimExpr &b)
Definition: broadcast.h:227
constexpr auto kCommReduce
Definition: tags.h:34
tvm::PrimExpr add(const tvm::PrimExpr &a, const tvm::PrimExpr &b)
Definition: broadcast.h:199
std::vector< int > GetRealAxis(int ndim, const ffi::Optional< ffi::Array< int64_t >> &axis)
Convert a reduction axis which could be empty or have negative elements into a real axis with valid d...
Definition: reduction.h:65
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition: analyzer.h:40
PrimExpr rsqrt(PrimExpr x, Span span=Span())
Definition: op.h:768
Operation node can generate one or multiple Tensors.
Tag definitions.