tvm
Loading...
Searching...
No Matches
softmax.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_SOFTMAX_H_
25#define TVM_TOPI_NN_SOFTMAX_H_
26
27#include <tvm/te/operation.h>
28#include <tvm/topi/reduction.h>
29#include <tvm/topi/tags.h>
30
31#include <algorithm>
32#include <string>
33
34namespace tvm {
35namespace topi {
36namespace nn {
37
38using namespace tvm::te;
39
50inline Tensor softmax(const Tensor& x, int axis = -1, std::string name = "tensor",
51 std::string tag = "softmax_output") {
52 auto input_shape = x->shape;
53 auto ndim = input_shape.size();
54 if (axis < 0) {
55 axis = ndim + axis;
56 }
57 TVM_FFI_ICHECK_LT(axis, ndim) << "axis parameter should be less than input dim";
58
59 auto k1 = tvm::te::reduce_axis(Range(0, input_shape[axis]), "k1");
60 auto k2 = tvm::te::reduce_axis(Range(0, input_shape[axis]), "k2");
61 auto reduced_shape = MakeReduceTargetShape({axis}, x, false, false);
62
63 tvm::ffi::Map<ffi::String, ffi::Any> attrs;
64 attrs.Set("axis", IntImm::Int32(axis));
65
66 auto insert_reduce_index = [axis, ndim](const ffi::Array<PrimVar>& indices,
67 const IterVar& reduce_index) {
68 ffi::Array<PrimExpr> eval_range;
69 int arg_counter = 0;
70 for (size_t i = 0; i < ndim; ++i) {
71 if (static_cast<int>(i) == axis) {
72 eval_range.push_back(reduce_index);
73 } else {
74 eval_range.push_back(indices[arg_counter++]);
75 }
76 }
77 return eval_range;
78 };
79
80 auto get_non_reduce_indices = [axis, ndim](const ffi::Array<PrimVar>& indices) {
81 ffi::Array<PrimExpr> non_reduce_indices;
82 for (size_t i = 0; i < ndim; ++i) {
83 if (static_cast<int>(i) != axis) non_reduce_indices.push_back(indices[i]);
84 }
85 return non_reduce_indices;
86 };
87
88 auto _compute_max = [&](const ffi::Array<PrimVar>& indices) {
89 auto eval_range = insert_reduce_index(indices, k1);
90 return topi::MaxOp(x(eval_range), {k1});
91 };
92
93 auto _compute_exp = [&](const Tensor& max_elem, const ffi::Array<PrimVar>& indices) {
95 return tvm::exp(x(indices) - max_elem(non_reduce_indices));
96 };
97
98 auto _compute_expsum = [&](const Tensor& exp, const ffi::Array<PrimVar>& indices) {
99 auto eval_range = insert_reduce_index(indices, k2);
100 return tvm::sum(exp(eval_range), {k2});
101 };
102
103 auto _normalize = [&](const Tensor& exp, const Tensor& expsum,
104 const ffi::Array<PrimVar>& indices) {
106 return exp(indices) / expsum(non_reduce_indices);
107 };
108
110 auto exp = tvm::te::compute(input_shape, [&](const ffi::Array<PrimVar>& indices) {
111 return _compute_exp(max_elem, indices);
112 });
113 auto expsum = tvm::te::compute(reduced_shape, [&](const ffi::Array<PrimVar>& indices) {
114 return _compute_expsum(exp, indices);
115 });
116 return tvm::te::compute(
118 [&](const ffi::Array<PrimVar>& indices) { return _normalize(exp, expsum, indices); }, name,
119 tag, attrs);
120}
121
131inline Tensor log_softmax(const Tensor& x, std::string name = "tensor",
132 std::string tag = "log_softmax_output") {
133 TVM_FFI_ICHECK_EQ(x->shape.size(), 2) << "Log softmax requires 2-D input";
134
135 PrimExpr m = x->shape[0];
136 PrimExpr n = x->shape[1];
137
138 auto k = tvm::te::reduce_axis(Range(0, n), "k");
139 auto max_elem =
140 tvm::te::compute({m}, [&](PrimVar i) { return tvm::max(x(i, k), ffi::Array<IterVar>{k}); });
141 k = tvm::te::reduce_axis(Range(0, n), "k");
142
144 {m}, [&](PrimVar i) { return tvm::sum(tvm::exp(x(i, k) - max_elem(i)), {k}); });
145
146 return tvm::te::compute(
147 x->shape, [&](PrimVar i, PrimVar j) { return x(i, j) - max_elem(i) - tvm::log(expsum(i)); },
148 name, tag);
149}
150
151} // namespace nn
152} // namespace topi
153} // namespace tvm
154#endif // TVM_TOPI_NN_SOFTMAX_H_
static IntImm Int32(int64_t value, Span span=Span())
Construct a scalar int32 constant.
Definition expr.h:528
Typed reference/view over any Expr whose ExprNode::ty is PrimType.
Definition base_expr.h:401
Range container
Definition expr.h:610
RAII wrapper function to enter and exit a context object similar to python's with syntax.
Definition with_context.h:59
Tensor structure representing a possible input, or intermediate computation result.
Definition tensor.h:98
Iteration Variable, represents an iteration over an integer interval.
Definition var.h:194
Checked scalar view over a VarNode.
Definition var.h:46
Tensor expression language DSL.
Definition extracted_task.h:33
IterVar reduce_axis(Range dom, std::string name="rv")
Create a new IterVar for reduction operations.
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...
const Op & exp()
Tensor softmax(const Tensor &x, int axis=-1, std::string name="tensor", std::string tag="softmax_output")
Softmax activation.
Definition softmax.h:50
Tensor log_softmax(const Tensor &x, std::string name="tensor", std::string tag="log_softmax_output")
Log softmax activation.
Definition softmax.h:131
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
PrimExpr MaxOp(PrimExpr source, ffi::Array< IterVar > axis, ffi::Array< PrimExpr > init={}, Span span=Span())
Wrap tvm::max to ensure we get the correct overload.
Definition reduction.h:313
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition analyzer.h:40
PrimExpr max(PrimExpr a, PrimExpr b, Span span=Span())
take maximum of two values
PrimExpr exp(PrimExpr x, Span span=Span())
Definition op.h:752
PrimExpr sum(PrimExpr source, ffi::Array< tirx::IterVar > axis, ffi::Array< PrimExpr > init={}, Span span=Span())
sum of source expression over axis
Operation node can generate one or multiple Tensors.
Reduction op constructors.
Tag definitions.