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 Tensor& beta,
53 const ffi::Array<int64_t>& axis, double epsilon,
54 std::string name = "T_layer_norm", std::string tag = kInjective) {
55 const auto& data_type = data->dtype;
56 const auto& gamma_type = gamma.defined() ? gamma->dtype : data_type;
57 const auto& beta_type = beta.defined() ? beta->dtype : data_type;
59 << "layer_norm: data, gamma and beta must have the same type";
61 << "layer_norm: only support float32 and float16 for now";
63 // Two-pass algorithm for improved numerical stability:
64 // pass1: mean = E[x]
65 // pass2: var = E[(x - mean)^2]
66 auto ndim = data->shape.size();
67 TVM_FFI_ICHECK_NE(ndim, 0) << "Cannot reduce a 0 dim Tensor";
68 auto real_axis = GetRealAxis(static_cast<int>(ndim), axis);
70 auto target_shape =
71 MakeReduceTargetShape(real_axis, data, /*keepdims=*/false, /*atleast1d=*/false);
73
75 ndim](const ffi::Array<PrimVar>& non_reduce_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 {
88 }
89 }
90 return eval_range;
91 };
92
96 f32_ty](const ffi::Array<PrimVar>& indices) {
97 auto eval_range = make_eval_range(indices);
98 PrimExpr x = data(eval_range);
99 if (is_float16) {
100 x = prim::Cast(f32_ty, x);
101 }
102 return sum(x, reduce_axes);
103 },
104 data->op->name + "_sum", kCommReduce);
105
108 for (int i : real_axis) {
109 reduce_extent *= data->shape[i];
110 }
113 [&temp_sum, &reduce_extent](const ffi::Array<PrimVar>& indices) {
114 return temp_sum(indices) / reduce_extent;
115 },
116 data->op->name + "_mean", kInjective);
117
121 f32_ty](const ffi::Array<PrimVar>& indices) {
122 auto eval_range = make_eval_range(indices);
123 PrimExpr x = data(eval_range);
124 if (is_float16) {
125 x = prim::Cast(f32_ty, x);
126 }
127 PrimExpr diff = x - temp_mean(indices);
128 return sum(diff * diff, reduce_axes);
129 },
130 data->op->name + "_var_sum", kCommReduce);
131
132 auto layer_norm_func = [&](const ffi::Array<PrimVar>& indices) {
133 ffi::Array<PrimVar> reduce_indices, non_reduce_indices;
134 for (int i = 0, n = static_cast<int>(indices.size()); i < n; ++i) {
135 if (std::find(real_axis.begin(), real_axis.end(), i) != real_axis.end()) {
136 reduce_indices.push_back(indices[i]);
137 } else {
138 non_reduce_indices.push_back(indices[i]);
139 }
140 }
143 auto layer_norm = (data(indices) - mean) * rsqrt(var + MakeConst(var.ty(), epsilon));
144 if (is_float16) {
146 }
148 if (beta.defined()) {
150 }
151 return layer_norm;
152 };
153 return te::compute(data->shape, layer_norm_func, name, tag);
154}
155
156} // namespace nn
157} // namespace topi
158} // namespace tvm
159
160#endif // TVM_TOPI_NN_LAYER_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
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
const Op & sum()
Tensor layer_norm(const Tensor &data, const Tensor &gamma, const 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: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
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
Tensor rsqrt(const Tensor &x, std::string name="tensor", std::string tag=kElementWise)
Creates an operation that returns rsqrt of a given tensor.
Definition elemwise.h:234
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition analyzer.h:40
Operation node can generate one or multiple Tensors.
Reduction op constructors.
Tag definitions.