tvm
Loading...
Searching...
No Matches
layer_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_LAYER_NORM_H_
25#define TVM_TOPI_NN_LAYER_NORM_H_
26
27#include <tvm/te/operation.h>
28#include <tvm/topi/reduction.h>
29#include <tvm/topi/tags.h>
30
31#include <string>
32
33namespace tvm {
34namespace topi {
35namespace nn {
36
37using namespace tvm::te;
38
52inline Tensor layer_norm(const Tensor& data, const Tensor& gamma, const ffi::Optional<Tensor>& beta,
53 const ffi::Array<int64_t>& axis, double epsilon,
54 std::string name = "T_layer_norm", std::string tag = kInjective) {
55 using namespace tvm::prim;
56 const auto& data_type = data->dtype;
57 const auto& gamma_type = gamma->dtype;
58 const auto& beta_type = beta.has_value() ? beta.value()->dtype : data_type;
59 TVM_FFI_ICHECK(data_type == gamma_type && data_type == beta_type)
60 << "layer_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 << "layer_norm: only support float32 and float16 for now";
63 bool is_float16 = data_type == PrimType::Float(16);
64 // Two-pass algorithm for improved numerical stability:
65 // pass1: mean = E[x]
66 // pass2: var = E[(x - mean)^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=*/false);
73 PrimType f32_ty = PrimType::Float(32);
74
75 auto make_eval_range = [&real_axis, &reduce_axes,
76 ndim](const ffi::Array<PrimVar>& non_reduce_indices) {
77 ffi::Array<PrimExpr> eval_range;
78 int arg_counter = 0;
79 int red_counter = 0;
80
81 for (size_t i = 0; i < ndim; ++i) {
82 if (std::find(real_axis.begin(), real_axis.end(), i) != real_axis.end()) {
83 // real_axis contains i
84 eval_range.push_back(reduce_axes[red_counter]);
85 red_counter++;
86 } else {
87 eval_range.push_back(non_reduce_indices[arg_counter]);
88 arg_counter++;
89 }
90 }
91 return eval_range;
92 };
93
94 Tensor temp_sum = te::compute(
95 target_shape,
96 [is_float16, &data, &reduce_axes, &make_eval_range,
97 f32_ty](const ffi::Array<PrimVar>& indices) {
98 auto eval_range = make_eval_range(indices);
99 PrimExpr x = data(eval_range);
100 if (is_float16) {
101 x = prim::Cast(f32_ty, x);
102 }
103 return prim::sum(x, reduce_axes);
104 },
105 data->op.value()->name + "_sum", kCommReduce);
106
107 PrimType reduce_dtype = is_float16 ? PrimType::Float(32) : PrimType(data->dtype);
108 PrimExpr reduce_extent = MakeConst(reduce_dtype, 1);
109 for (int i : real_axis) {
110 reduce_extent *= data->shape[i];
111 }
112 Tensor temp_mean = te::compute(
113 target_shape,
114 [&temp_sum, &reduce_extent](const ffi::Array<PrimVar>& indices) {
115 return temp_sum(indices) / reduce_extent;
116 },
117 data->op.value()->name + "_mean", kInjective);
118
119 Tensor temp_var_sum = te::compute(
120 target_shape,
121 [is_float16, &data, &reduce_axes, &make_eval_range, &temp_mean,
122 f32_ty](const ffi::Array<PrimVar>& indices) {
123 auto eval_range = make_eval_range(indices);
124 PrimExpr x = data(eval_range);
125 if (is_float16) {
126 x = prim::Cast(f32_ty, x);
127 }
128 PrimExpr diff = x - temp_mean(indices);
129 return prim::sum(diff * diff, reduce_axes);
130 },
131 data->op.value()->name + "_var_sum", kCommReduce);
132
133 auto layer_norm_func = [&](const ffi::Array<PrimVar>& indices) {
134 ffi::Array<PrimVar> reduce_indices, non_reduce_indices;
135 for (int i = 0, n = static_cast<int>(indices.size()); i < n; ++i) {
136 if (std::find(real_axis.begin(), real_axis.end(), i) != real_axis.end()) {
137 reduce_indices.push_back(indices[i]);
138 } else {
139 non_reduce_indices.push_back(indices[i]);
140 }
141 }
142 auto mean = temp_mean(non_reduce_indices);
143 auto var = temp_var_sum(non_reduce_indices) / reduce_extent;
144 auto layer_norm = (data(indices) - mean) * prim::rsqrt(var + MakeConst(var.ty(), epsilon));
145 if (is_float16) {
147 }
148 layer_norm = topi::multiply(layer_norm, gamma(reduce_indices));
149 if (beta.has_value()) {
150 layer_norm = topi::add(layer_norm, beta.value()(reduce_indices));
151 }
152 return layer_norm;
153 };
154 return te::compute(data->shape, layer_norm_func, name, tag);
155}
156
157} // namespace nn
158} // namespace topi
159} // namespace tvm
160
161#endif // TVM_TOPI_NN_LAYER_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.
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 sum(PrimExpr source, ffi::Array< s_tir::IterVar > axis, ffi::Array< PrimExpr > init={}, Location loc=UnknownLoc())
sum of source expression over axis
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 layer_norm(const Tensor &data, const Tensor &gamma, const ffi::Optional< Tensor > &beta, const ffi::Array< int64_t > &axis, double epsilon, std::string name="T_layer_norm", std::string tag=kInjective)
Layer normalization.
Definition layer_norm.h:52
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
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.
Reduction op constructors.