• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <any>
20 #include <cstdint>
21 #include <cstring>
22 #include <memory>
23 #include <string>
24 #include <utility>
25 #include <vector>
26 
27 #include "absl/memory/memory.h"
28 #include "tensorflow/lite/delegates/gpu/common/status.h"
29 #include "tensorflow/lite/delegates/gpu/common/types.h"
30 #include "tensorflow/lite/delegates/gpu/gl/variable.h"
31 
32 namespace tflite {
33 namespace gpu {
34 namespace gl {
35 namespace {
36 
37 class ReLU : public NodeShader {
38  public:
GenerateCode(const GenerationContext & ctx,GeneratedCode * generated_code) const39   absl::Status GenerateCode(const GenerationContext& ctx,
40                             GeneratedCode* generated_code) const final {
41     const auto& attr = std::any_cast<const ReLUAttributes&>(ctx.op_attr);
42     // clamp(value, min(0, alpha * value), clip)
43     std::vector<Variable> params;
44     std::string min;
45     if (attr.alpha == 0) {
46       min = "vec4(0.0)";
47     } else {
48       min = "min($alpha$ * value_0, 0.0)";
49       params.push_back({"alpha", attr.alpha});
50     }
51     std::string code;
52     if (attr.clip == 0) {
53       code = "value_0 = max(value_0, " + min + ");";
54     } else {
55       code = "value_0 = clamp(value_0, " + min + ", vec4($clip$));";
56       params.push_back({"clip", attr.clip});
57     }
58     *generated_code = {
59         /*parameters=*/std::move(params),
60         /*objects=*/{},
61         /*shared_variables=*/{},
62         /*workload=*/uint3(),
63         /*workgroup=*/uint3(),
64         /*source_code=*/std::move(code),
65         /*input=*/IOStructure::AUTO,
66         /*output=*/IOStructure::AUTO,
67     };
68     return absl::OkStatus();
69   }
70 };
71 
72 }  // namespace
73 
NewReLUNodeShader()74 std::unique_ptr<NodeShader> NewReLUNodeShader() {
75   return std::make_unique<ReLU>();
76 }
77 
78 }  // namespace gl
79 }  // namespace gpu
80 }  // namespace tflite
81