1 /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 #include "tensorflow/lite/delegates/gpu/gl/kernels/relu.h"
17
18 #include <algorithm>
19 #include <cstdint>
20 #include <cstring>
21 #include <string>
22 #include <vector>
23
24 #include "absl/memory/memory.h"
25 #include "tensorflow/lite/delegates/gpu/common/status.h"
26 #include "tensorflow/lite/delegates/gpu/common/types.h"
27 #include "tensorflow/lite/delegates/gpu/gl/variable.h"
28
29 namespace tflite {
30 namespace gpu {
31 namespace gl {
32 namespace {
33
34 class ReLU : public NodeShader {
35 public:
GenerateCode(const GenerationContext & ctx,GeneratedCode * generated_code) const36 absl::Status GenerateCode(const GenerationContext& ctx,
37 GeneratedCode* generated_code) const final {
38 const auto& attr = absl::any_cast<const ReLUAttributes&>(ctx.op_attr);
39 // clamp(value, min(0, alpha * value), clip)
40 std::vector<Variable> params;
41 std::string min;
42 if (attr.alpha == 0) {
43 min = "vec4(0.0)";
44 } else {
45 min = "min($alpha$ * value_0, 0.0)";
46 params.push_back({"alpha", attr.alpha});
47 }
48 std::string code;
49 if (attr.clip == 0) {
50 code = "value_0 = max(value_0, " + min + ");";
51 } else {
52 code = "value_0 = clamp(value_0, " + min + ", vec4($clip$));";
53 params.push_back({"clip", attr.clip});
54 }
55 *generated_code = {
56 /*parameters=*/std::move(params),
57 /*objects=*/{},
58 /*shared_variables=*/{},
59 /*workload=*/uint3(),
60 /*workgroup=*/uint3(),
61 /*source_code=*/std::move(code),
62 /*input=*/IOStructure::AUTO,
63 /*output=*/IOStructure::AUTO,
64 };
65 return absl::OkStatus();
66 }
67 };
68
69 } // namespace
70
NewReLUNodeShader()71 std::unique_ptr<NodeShader> NewReLUNodeShader() {
72 return absl::make_unique<ReLU>();
73 }
74
75 } // namespace gl
76 } // namespace gpu
77 } // namespace tflite
78