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