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, 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;
60 << "instance_norm: data, gamma and beta must have the same type";
62 << "instance_norm: only support float32 and float16 for now";
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);
69 auto target_shape =
70 MakeReduceTargetShape(real_axis, data, /*keepdims=*/false, /*atleast1d=*/true);
71 auto func = MakeTupleSumReducer();
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
85 } else {
86 eval_range.push_back(indices[arg_counter]);
88 }
89 }
90 auto square = [is_float16, f32_ty](const PrimExpr& x) {
91 if (is_float16) {
92 return prim::Cast(f32_ty, x) * prim::Cast(f32_ty, x);
93 }
94 return x * x;
95 };
96 if (is_float16) {
97 return func({prim::Cast(f32_ty, data(eval_range)), square(data(eval_range))}, reduce_axes,
98 nullptr);
99 } else {
100 return func({data(eval_range), square(data(eval_range))}, reduce_axes, nullptr);
101 }
102 };
103
104 auto temp_x_x2 =
105 tvm::te::compute(target_shape, compute, data->op->name + "_red_temp", kCommReduce);
106
107 auto temp_x = temp_x_x2[0];
108 auto temp_x2 = temp_x_x2[1];
109
110 auto reduce_extent = MakeConst(PrimType(data->dtype), 1);
111 for (int i : real_axis) {
112 reduce_extent *= data->shape[i];
113 }
114 auto instance_norm_func = [&](const ffi::Array<PrimVar>& indices) {
115 ffi::Array<PrimVar> reduce_indices, non_reduce_indices;
116
117 for (int i = 0, n = static_cast<int>(indices.size()); i < n; ++i) {
118 if (std::find(real_axis.begin(), real_axis.end(), i) != real_axis.end()) {
119 reduce_indices.push_back(indices[i]);
120 } else {
121 non_reduce_indices.push_back(indices[i]);
122 }
123 }
124 PrimVar channel;
125 channel = indices[channel_axis];
128 auto instance_norm = (data(indices) - mean) * tvm::rsqrt(var + MakeConst(var.ty(), epsilon));
129 if (is_float16) {
131 }
133 if (beta.defined()) {
134 instance_norm = topi::add(instance_norm, beta(channel));
135 }
136 return instance_norm;
137 };
138 return tvm::te::compute(data->shape, instance_norm_func, name, tag);
139}
140
141} // namespace nn
142} // namespace topi
143} // namespace tvm
144
145#endif // TVM_TOPI_NN_INSTANCE_NORM_H_
Typed reference/view over any Expr whose ExprNode::ty is PrimType.
Definition base_expr.h:401
Definition base_expr.h:137
static PrimType Float(int bits, int lanes=1)
Construct a floating-point type with fixed lanes.
ExpectedType ty() const
Definition base_expr.h:380
RAII wrapper function to enter and exit a context object similar to python's with syntax.
Definition with_context.h:59
Managed reference to CastNode.
Definition expr.h:95
Tensor structure representing a possible input, or intermediate computation result.
Definition tensor.h:98
Checked scalar view over a VarNode.
Definition var.h:46
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...
@ kCommReduce
Communicative reduction. Cannot be directly parallelized.
Definition var.h:104
const Op & add()
PrimExpr MakeConst(PrimType dtype, ValueType value, Span span=Span())
Make a const value with certain data type.
Definition op.h:1002
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
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
ffi::Array< IterVar > MakeReduceAxes(const std::vector< int > &real_axis, const Tensor &data)
Enumerate the axes for a reduce op.
Definition reduction.h:89
FCommReduce MakeTupleSumReducer()
Create communitive reducer summing over tuples.
Definition reduction.h:601
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
constexpr auto kInjective
Definition tags.h:33
tvm::PrimExpr multiply(const tvm::PrimExpr &a, const tvm::PrimExpr &b)
Definition broadcast.h:227
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:759
Operation node can generate one or multiple Tensors.
Tag definitions.