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 Tensor& gamma, const Tensor& beta,
40 int num_groups, int channel_axis, const ffi::Array<int64_t>& axes,
41 double epsilon, std::string name = "T_group_norm",
42 std::string tag = kInjective) {
43 const auto& data_type = data->dtype;
44 const auto& gamma_type = gamma.defined() ? gamma->dtype : data_type;
45 const auto& beta_type = beta.defined() ? beta->dtype : data_type;
47 << "group_norm: data, gamma and beta must have the same type";
49 << "group_norm: only support float32 and float16 for now";
51 // reshape data C -> G, C/G
52 int ndim = data->shape.size();
53 channel_axis = GetRealAxis(static_cast<int>(ndim), ffi::Array<int64_t>({channel_axis}))[0];
54
55 auto shape = data->shape;
56 auto group_size = floordiv(shape[channel_axis], num_groups);
57 auto new_shape = ffi::Array<PrimExpr>();
58 for (int i = 0; i < ndim; ++i) {
59 if (i == channel_axis) {
60 new_shape.push_back(num_groups);
61 new_shape.push_back(group_size);
62 } else {
63 new_shape.push_back(shape[i]);
64 }
65 }
67 if (is_float16) {
69 } else {
71 }
72 // reshape gamma and beta, C -> G, C/G, cast to float32 if float16
74 if (gamma.defined()) {
75 gamma_reshaped = reshape(gamma, {num_groups, group_size});
76 }
78 if (beta.defined()) {
79 beta_reshaped = reshape(beta, {num_groups, group_size});
80 }
81
82 // get the new axes to normalize after reshape
83 std::vector<int> new_axes{channel_axis + 1};
84 for (auto axis : axes) {
85 int new_axis = GetRealAxis(static_cast<int>(ndim), ffi::Array<int64_t>({axis}))[0];
86 if (new_axis < channel_axis) {
87 new_axes.push_back(new_axis);
88 } else if (new_axis > channel_axis) {
89 new_axes.push_back(new_axis + 1);
90 } else {
91 TVM_FFI_ICHECK(false) << "axes can not contain channel axis";
92 }
93 }
94 std::sort(new_axes.begin(), new_axes.end());
95
96 // sum x and x^2, cast to float32 if float16
97 ndim = data_reshaped->shape.size();
99 auto target_shape =
100 MakeReduceTargetShape(new_axes, data_reshaped, /*keepdims=*/false, /*atleast1d=*/true);
101 auto func = MakeTupleSumReducer();
102
103 auto compute = [ndim, &new_axes, &reduce_axes, &func,
104 &data_reshaped](const ffi::Array<PrimVar>& indices) {
105 ffi::Array<PrimExpr> eval_range;
106 int arg_counter = 0;
107 int red_counter = 0;
108
109 for (int i = 0; i < ndim; ++i) {
110 if (std::find(new_axes.begin(), new_axes.end(), i) != new_axes.end()) {
111 // new_axes contains i
113 red_counter++;
114 } else {
115 eval_range.push_back(indices[arg_counter]);
116 arg_counter++;
117 }
118 }
119 auto square = [](const PrimExpr& x) { return x * x; };
121 nullptr);
122 };
123
124 auto temp_x_x2 =
125 tvm::te::compute(target_shape, compute, data->op->name + "_red_temp", kCommReduce);
126
127 auto temp_x = temp_x_x2[0];
128 auto temp_x2 = temp_x_x2[1];
130 for (auto axis : new_axes) {
131 reduce_extent *= data_reshaped->shape[axis];
132 }
133 auto group_norm_func = [&](const ffi::Array<PrimVar>& indices) {
134 ffi::Array<PrimVar> reduce_indices, non_reduce_indices, gamma_indices;
135 for (int i = 0, n = static_cast<int>(indices.size()); i < n; ++i) {
136 if (std::find(new_axes.begin(), new_axes.end(), i) != new_axes.end()) {
137 reduce_indices.push_back(indices[i]);
138 } else {
139 non_reduce_indices.push_back(indices[i]);
140 }
141 }
142 gamma_indices = {indices[channel_axis], indices[channel_axis + 1]};
145 PrimExpr group_norm = (data_reshaped(indices) - mean) *
146 tvm::rsqrt(var + MakeConst(PrimType(data->dtype), epsilon));
147 if (is_float16) {
149 }
150 if (gamma.defined()) {
152 }
153 if (beta.defined()) {
155 }
156 return group_norm;
157 };
161}
162
163} // namespace nn
164} // namespace topi
165} // namespace tvm
166
167#endif // TVM_TOPI_NN_GROUP_NORM_H_
Managed reference class to FloatImmNode.
Definition expr.h:567
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.
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
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 & cast()
See pesudo code below:
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 group_norm(const Tensor &data, const Tensor &gamma, const 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:99
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:2009
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
PrimExpr floordiv(PrimExpr a, PrimExpr b, Span span=Span())
compute floor(a / b)
Operation node can generate one or multiple Tensors.