tvm
Loading...
Searching...
No Matches
group_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_GROUP_NORM_H_
25#define TVM_TOPI_NN_GROUP_NORM_H_
26
27#include <tvm/te/operation.h>
28
29#include <algorithm>
30#include <string>
31#include <vector>
32
33namespace tvm {
34namespace topi {
35namespace nn {
36
37using namespace tvm::te;
38
39inline Tensor group_norm(const Tensor& data, const ffi::Optional<Tensor>& gamma,
40 const ffi::Optional<Tensor>& beta, int num_groups, int channel_axis,
41 const ffi::Array<int64_t>& axes, double epsilon,
42 std::string name = "T_group_norm", std::string tag = kInjective) {
43 using namespace tvm::prim;
44 const auto& data_type = data->dtype;
45 const auto& gamma_type = gamma.has_value() ? gamma.value()->dtype : data_type;
46 const auto& beta_type = beta.has_value() ? beta.value()->dtype : data_type;
47 TVM_FFI_ICHECK(data_type == gamma_type && data_type == beta_type)
48 << "group_norm: data, gamma and beta must have the same type";
49 TVM_FFI_ICHECK(data_type == PrimType::Float(32) || data_type == PrimType::Float(16))
50 << "group_norm: only support float32 and float16 for now";
51 bool is_float16 = data_type == PrimType::Float(16);
52 // reshape data C -> G, C/G
53 int ndim = data->shape.size();
54 channel_axis = GetRealAxis(static_cast<int>(ndim), ffi::Array<int64_t>({channel_axis}))[0];
55
56 auto shape = data->shape;
57 auto group_size = floordiv(shape[channel_axis], num_groups);
58 auto new_shape = ffi::Array<PrimExpr>();
59 for (int i = 0; i < ndim; ++i) {
60 if (i == channel_axis) {
61 new_shape.push_back(num_groups);
62 new_shape.push_back(group_size);
63 } else {
64 new_shape.push_back(shape[i]);
65 }
66 }
67 Tensor data_reshaped = reshape(data, new_shape);
68 if (is_float16) {
69 data_reshaped = cast(data_reshaped, PrimType::Float(32));
70 }
71 // reshape gamma and beta, C -> G, C/G, cast to float32 if float16
72 ffi::Optional<Tensor> gamma_reshaped;
73 if (gamma.has_value()) {
74 gamma_reshaped = reshape(gamma.value(), {num_groups, group_size});
75 }
76 ffi::Optional<Tensor> beta_reshaped;
77 if (beta.has_value()) {
78 beta_reshaped = reshape(beta.value(), {num_groups, group_size});
79 }
80
81 // get the new axes to normalize after reshape
82 std::vector<int> new_axes{channel_axis + 1};
83 for (auto axis : axes) {
84 int new_axis = GetRealAxis(static_cast<int>(ndim), ffi::Array<int64_t>({axis}))[0];
85 if (new_axis < channel_axis) {
86 new_axes.push_back(new_axis);
87 } else if (new_axis > channel_axis) {
88 new_axes.push_back(new_axis + 1);
89 } else {
90 TVM_FFI_ICHECK(false) << "axes can not contain channel axis";
91 }
92 }
93 std::sort(new_axes.begin(), new_axes.end());
94
95 // sum x and x^2, cast to float32 if float16
96 ndim = data_reshaped->shape.size();
97 auto reduce_axes = MakeReduceAxes(new_axes, data_reshaped);
98 auto target_shape =
99 MakeReduceTargetShape(new_axes, data_reshaped, /*keepdims=*/false, /*atleast1d=*/true);
100 auto func = MakeTupleSumReducer();
101
102 auto compute = [ndim, &new_axes, &reduce_axes, &func,
103 &data_reshaped](const ffi::Array<PrimVar>& indices) {
104 ffi::Array<PrimExpr> eval_range;
105 int arg_counter = 0;
106 int red_counter = 0;
107
108 for (int i = 0; i < ndim; ++i) {
109 if (std::find(new_axes.begin(), new_axes.end(), i) != new_axes.end()) {
110 // new_axes contains i
111 eval_range.push_back(reduce_axes[red_counter]);
112 red_counter++;
113 } else {
114 eval_range.push_back(indices[arg_counter]);
115 arg_counter++;
116 }
117 }
118 auto square = [](const PrimExpr& x) { return x * x; };
119 return func({data_reshaped(eval_range), square(data_reshaped(eval_range))}, reduce_axes,
120 nullptr);
121 };
122
123 auto temp_x_x2 =
124 tvm::te::compute(target_shape, compute, data->op.value()->name + "_red_temp", kCommReduce);
125
126 auto temp_x = temp_x_x2[0];
127 auto temp_x2 = temp_x_x2[1];
128 PrimExpr reduce_extent = FloatImm(PrimType::Float(32), 1);
129 for (auto axis : new_axes) {
130 reduce_extent *= data_reshaped->shape[axis];
131 }
132 auto group_norm_func = [&](const ffi::Array<PrimVar>& indices) {
133 ffi::Array<PrimVar> reduce_indices, non_reduce_indices, gamma_indices;
134 for (int i = 0, n = static_cast<int>(indices.size()); i < n; ++i) {
135 if (std::find(new_axes.begin(), new_axes.end(), i) != new_axes.end()) {
136 reduce_indices.push_back(indices[i]);
137 } else {
138 non_reduce_indices.push_back(indices[i]);
139 }
140 }
141 gamma_indices = {indices[channel_axis], indices[channel_axis + 1]};
142 auto mean = temp_x(non_reduce_indices) / reduce_extent;
143 auto var = temp_x2(non_reduce_indices) / reduce_extent - mean * mean;
144 PrimExpr group_norm = (data_reshaped(indices) - mean) *
145 tvm::prim::rsqrt(var + MakeConst(PrimType(data->dtype), epsilon));
146 if (is_float16) {
148 }
149 if (gamma.has_value()) {
150 group_norm = topi::multiply(group_norm, gamma_reshaped.value()(gamma_indices));
151 }
152 if (beta.has_value()) {
153 group_norm = topi::add(group_norm, beta_reshaped.value()(gamma_indices));
154 }
155 return group_norm;
156 };
157 auto group_norm_out = tvm::te::compute(data_reshaped->shape, group_norm_func, name, tag);
158 auto group_norm_out_reshaped = reshape(group_norm_out, shape);
159 return group_norm_out_reshaped;
160}
161
162} // namespace nn
163} // namespace topi
164} // namespace tvm
165
166#endif // TVM_TOPI_NN_GROUP_NORM_H_
Managed reference class to FloatImmNode.
Definition expr.h:232
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.
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 group_norm(const Tensor &data, const ffi::Optional< Tensor > &gamma, const ffi::Optional< Tensor > &beta, int num_groups, int channel_axis, const ffi::Array< int64_t > &axes, double epsilon, std::string name="T_group_norm", std::string tag=kInjective)
Definition group_norm.h:39
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
Tensor reshape(const Tensor &x, ffi::Array< PrimExpr > newshape, std::string name="T_reshape", std::string tag=kInjective)
Reshape a tensor.
Definition transform.h:329
Tensor shape(const Tensor &src, PrimType dtype, const std::string name="T_shape", const std::string tag=kInjective)
Get the shape of input tensor.
Definition transform.h:2016
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
Tensor cast(const Tensor &x, PrimType type, std::string name, std::string tag)
Cast each element of x to the given type. If expr is scalar and type is a corresponding vector type,...
Definition elemwise.h:291
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition attr.h:23
TVM_TIRX_DLL PrimExpr floordiv(PrimExpr a, PrimExpr b, Location loc=UnknownLoc())
compute floor(a / b)
Operation node can generate one or multiple Tensors.