tvm
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 
33 namespace tvm {
34 namespace topi {
35 namespace nn {
36 
37 using namespace tvm::te;
38 
52 inline 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;
58  TVM_FFI_ICHECK(data_type == gamma_type && data_type == beta_type)
59  << "layer_norm: data, gamma and beta must have the same type";
60  TVM_FFI_ICHECK(data_type == PrimType::Float(32) || data_type == PrimType::Float(16))
61  << "layer_norm: only support float32 and float16 for now";
62  bool is_float16 = data_type == PrimType::Float(16);
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);
69  auto reduce_axes = MakeReduceAxes(real_axis, data);
70  auto target_shape =
71  MakeReduceTargetShape(real_axis, data, /*keepdims=*/false, /*atleast1d=*/false);
72  PrimType f32_ty = PrimType::Float(32);
73 
74  auto make_eval_range = [&real_axis, &reduce_axes,
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
83  eval_range.push_back(reduce_axes[red_counter]);
84  red_counter++;
85  } else {
86  eval_range.push_back(non_reduce_indices[arg_counter]);
87  arg_counter++;
88  }
89  }
90  return eval_range;
91  };
92 
93  Tensor temp_sum = te::compute(
94  target_shape,
95  [is_float16, &data, &reduce_axes, &make_eval_range,
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 = Cast(f32_ty, x);
101  }
102  return sum(x, reduce_axes);
103  },
104  data->op->name + "_sum", kCommReduce);
105 
106  PrimType reduce_dtype = is_float16 ? PrimType::Float(32) : PrimType(data->dtype);
107  PrimExpr reduce_extent = MakeConst(reduce_dtype, 1);
108  for (int i : real_axis) {
109  reduce_extent *= data->shape[i];
110  }
111  Tensor temp_mean = te::compute(
112  target_shape,
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 
118  Tensor temp_var_sum = te::compute(
119  target_shape,
120  [is_float16, &data, &reduce_axes, &make_eval_range, &temp_mean,
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 = 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  }
141  auto mean = temp_mean(non_reduce_indices);
142  auto var = temp_var_sum(non_reduce_indices) / reduce_extent;
143  auto layer_norm = (data(indices) - mean) * rsqrt(var + MakeConst(var.ty(), epsilon));
144  if (is_float16) {
146  }
147  layer_norm = topi::multiply(layer_norm, gamma(reduce_indices));
148  if (beta.defined()) {
149  layer_norm = topi::add(layer_norm, beta(reduce_indices));
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:354
Definition: base_expr.h:113
static PrimType Float(int bits, int lanes=1)
Construct a floating-point type with fixed lanes.
ExpectedType ty() const
Definition: base_expr.h:333
Tensor structure representing a possible input, or intermediate computation result.
Definition: tensor.h:100
Managed reference to CastNode.
Definition: expr.h:96
Tensor expression language DSL.
Definition: extracted_task.h:32
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...
PrimExpr MakeConst(PrimType dtype, ValueType value, Span span=Span())
Make a const value with certain data type.
Definition: op.h:1012
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
Tensor sum(const Tensor &data, const ffi::Optional< ffi::Array< int64_t >> &axis, bool keepdims=false, bool atleast1d=false)
Creates an operation that sums array elements over a given axis.
Definition: reduction.h:337
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
constexpr auto kInjective
Definition: tags.h:33
ffi::Array< IterVar > MakeReduceAxes(const std::vector< int > &real_axis, const Tensor &data)
Enumerate the axes for a reduce op.
Definition: reduction.h:89
tvm::PrimExpr multiply(const tvm::PrimExpr &a, const tvm::PrimExpr &b)
Definition: broadcast.h:227
constexpr auto kCommReduce
Definition: tags.h:34
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:233
tvm::PrimExpr add(const tvm::PrimExpr &a, const tvm::PrimExpr &b)
Definition: broadcast.h:199
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
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.