blob: 798c6e48d5dfa2e3a5e9dc43846019275427ef59 [file] [log] [blame]
telsoa014fcda012018-03-09 14:13:49 +00001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
David Beckecb56cd2018-09-05 12:52:57 +01003// SPDX-License-Identifier: MIT
telsoa014fcda012018-03-09 14:13:49 +00004//
5
6#include "Activation.hpp"
7
telsoa014fcda012018-03-09 14:13:49 +00008#include <cmath>
9
10namespace armnn
11{
Colm Donelan03fbeaf2020-02-26 15:39:23 +000012
Nattapat Chaimanowongae2c5f02019-04-24 16:19:57 +010013float Activation(float in,
14 ActivationFunction function,
15 float a,
16 float b)
17{
18 float output;
19
20 // Compute the result of the activation function.
21 switch (function)
22 {
23 case ActivationFunction::Linear:
24 {
25 output = a * in + b;
26 break;
27 }
28 case ActivationFunction::Sigmoid:
29 {
30 output = 1.f / (1.f + expf(-in));
31 break;
32 }
33 case ActivationFunction::ReLu:
34 {
35 output = std::max(0.f, in);
36 break;
37 }
38 case ActivationFunction::BoundedReLu:
39 {
40 output = std::min(a, std::max(b, in));
41 break;
42 }
43 case ActivationFunction::SoftReLu:
44 {
45 output = logf(1.0f + expf(in));
46 break;
47 }
48 case ActivationFunction::LeakyReLu:
49 {
50 output = in > 0.0f ? in : (in * a);
51 break;
52 }
53 case ActivationFunction::Abs:
54 {
55 output = in < 0 ? -in : in;
56 break;
57 }
58 case ActivationFunction::Sqrt:
59 {
60 output = sqrtf(in);
61 break;
62 }
63 case ActivationFunction::Square:
64 {
65 output = in * in;
66 break;
67 }
68 case ActivationFunction::TanH:
69 {
70 output = a * tanhf(b * in);
71 break;
72 }
David Monahan3b3c3812020-02-25 09:03:29 +000073 case ActivationFunction::Elu:
74 {
75 output = (in >= 0) ? in : a * (expf(in) - 1);
76 break;
77 }
Colm Donelan03fbeaf2020-02-26 15:39:23 +000078 case ActivationFunction::HardSwish:
79 {
80 // hard_swish(x) = x * relu6(x+3) / 6
81 // relu6(x) = min(max(x,0),6)
82 output = in * (std::min(std::max((in + 3),0.0f),6.0f)) / 6;
83 break;
84 }
Nattapat Chaimanowongae2c5f02019-04-24 16:19:57 +010085 default:
86 {
87 throw InvalidArgumentException("Unsupported activation function");
88 }
89 }
90
91 return output;
92}
93
94
95void Activation(Decoder<float>& in,
96 Encoder<float>& out,
97 const TensorInfo& tensorInfo,
98 ActivationFunction function,
99 float a,
100 float b)
101{
Nattapat Chaimanowongeb2b3292019-05-07 12:02:30 +0100102 unsigned int numElements = tensorInfo.GetNumElements();
103
104 for (unsigned int i = 0; i < numElements; i++)
Nattapat Chaimanowongae2c5f02019-04-24 16:19:57 +0100105 {
106 out.Set(Activation(in.Get(), function, a, b));
Nattapat Chaimanowongae2c5f02019-04-24 16:19:57 +0100107 ++in;
108 ++out;
109 }
Nattapat Chaimanowongeb2b3292019-05-07 12:02:30 +0100110 in -= numElements;
111 out -= numElements;
telsoa014fcda012018-03-09 14:13:49 +0000112}
113
114} //namespace armnn