xref: /aosp_15_r20/external/tensorflow/tensorflow/lite/delegates/gpu/gl/kernels/add.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
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/add.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 <variant>
26 #include <vector>
27 
28 #include "absl/memory/memory.h"
29 #include "absl/strings/str_cat.h"
30 #include "tensorflow/lite/delegates/gpu/common/convert.h"
31 #include "tensorflow/lite/delegates/gpu/common/data_type.h"
32 #include "tensorflow/lite/delegates/gpu/common/status.h"
33 #include "tensorflow/lite/delegates/gpu/common/types.h"
34 
35 namespace tflite {
36 namespace gpu {
37 namespace gl {
38 namespace {
39 
40 class Add : public NodeShader {
41  public:
GenerateCode(const GenerationContext & ctx,GeneratedCode * generated_code) const42   absl::Status GenerateCode(const GenerationContext& ctx,
43                             GeneratedCode* generated_code) const final {
44     const auto& attr = std::any_cast<const ElementwiseAttributes&>(ctx.op_attr);
45     auto adds = std::get_if<Tensor<Linear, DataType::FLOAT32>>(&attr.param);
46     auto scalar = std::get_if<float>(&attr.param);
47 
48     const auto* hwc_tensor =
49         std::get_if<Tensor<HWC, DataType::FLOAT32>>(&attr.param);
50 
51     if (hwc_tensor) {
52       std::string code;
53       const std::string x_coord = hwc_tensor->shape.w == 1 ? "0" : "gid.x";
54       const std::string y_coord = hwc_tensor->shape.h == 1 ? "0" : "gid.y";
55       const std::string s_coord = hwc_tensor->shape.c == 1 ? "0" : "gid.z";
56       code = absl::StrCat("vec4 second_val = $hwc_buffer[", x_coord, ", ",
57                           y_coord, ", ", s_coord, "]$;\n");
58       if (hwc_tensor->shape.c == 1) {
59         code += "  second_val.y = second_val.x;\n";
60         code += "  second_val.z = second_val.x;\n";
61         code += "  second_val.w = second_val.x;\n";
62       }
63       code += "  value_0 += second_val;\n";
64       *generated_code = {
65           /*parameters=*/{},
66           /*objects=*/
67           {{"hwc_buffer",
68             MakeReadonlyObject(
69                 uint3(hwc_tensor->shape.w, hwc_tensor->shape.h,
70                       DivideRoundUp(hwc_tensor->shape.c, 4)),
71                 ConvertToPHWC4(
72                     std::get<Tensor<HWC, DataType::FLOAT32>>(attr.param)))}},
73           /*shared_variables=*/{},
74           // Declare workload explicitly because shader depends on gid.z.
75           /*workload=*/
76           uint3(static_cast<int>(ctx.input_shapes[0][2]),
77                 static_cast<int>(ctx.input_shapes[0][1]),
78                 DivideRoundUp(static_cast<int>(ctx.input_shapes[0][3]), 4)),
79           /*workgroup=*/uint3(),
80           /*source_code=*/std::move(code),
81           /*input=*/IOStructure::AUTO,
82           /*output=*/IOStructure::AUTO,
83       };
84       return absl::OkStatus();
85     }
86 
87     if (!adds && !scalar) {
88       // check if it is a broadcast
89       if (ctx.input_shapes.size() == 2 &&
90           ctx.input_shapes[0] != ctx.input_shapes[1] &&
91           ctx.input_shapes[1][1] == 1 && ctx.input_shapes[1][2] == 1 &&
92           ctx.input_shapes[0][3] == ctx.input_shapes[1][3]) {
93         // TODO(b/147771327): investigate why input_data_1[gid.z] worked before
94         *generated_code = {
95             /*parameters=*/{},
96             /*objects=*/{},
97             /*shared_variables=*/{},
98             /*workload=*/uint3(),
99             /*workgroup=*/uint3(),
100             /*source_code=*/
101             "value_0 = $input_data_0[gid.x, gid.y, gid.z]$ + "
102             "          $input_data_1[0, 0, gid.z]$;",
103             /*input=*/IOStructure::ONLY_DEFINITIONS,
104             /*output=*/IOStructure::AUTO,
105         };
106         return absl::OkStatus();
107       }
108 
109       std::string code = "value_0 = value_0";
110       for (int index = 1; index < ctx.input_shapes.size(); ++index) {
111         if (ctx.input_shapes[index] != ctx.input_shapes[0]) {
112           return absl::InvalidArgumentError("Shapes are not equal");
113         }
114         absl::StrAppend(&code, " + value_", index);
115       }
116       absl::StrAppend(&code, ";");
117       *generated_code = {
118           /*parameters=*/{},
119           /*objects=*/{},
120           /*shared_variables=*/{},
121           /*workload=*/uint3(),
122           /*workgroup=*/uint3(),
123           /*source_code=*/std::move(code),
124           /*input=*/IOStructure::AUTO,
125           /*output=*/IOStructure::AUTO,
126       };
127       return absl::OkStatus();
128     }
129 
130     if (scalar) {
131       *generated_code = {
132           /*parameters=*/{{"scalar", *scalar}},
133           /*objects=*/{},
134           /*shared_variables=*/{},
135           /*workload=*/uint3(),
136           /*workgroup=*/uint3(),
137           /*source_code=*/"value_0 += $scalar$;",
138           /*input=*/IOStructure::AUTO,
139           /*output=*/IOStructure::AUTO,
140       };
141       return absl::OkStatus();
142     }
143 
144     *generated_code = {
145         /*parameters=*/{},
146         /*objects=*/{{"add_buffer", MakeReadonlyObject(adds->data)}},
147         /*shared_variables=*/{},
148         // Declare workload explicitly because shader depends on gid.z.
149         /*workload=*/
150         uint3(ctx.input_shapes[0][2], ctx.input_shapes[0][1],
151               DivideRoundUp(ctx.input_shapes[0][3], 4)),
152         /*workgroup=*/uint3(),
153         /*source_code=*/"value_0 += $add_buffer[gid.z]$;",
154         /*input=*/IOStructure::AUTO,
155         /*output=*/IOStructure::AUTO,
156     };
157     return absl::OkStatus();
158   }
159 };
160 
161 }  // namespace
162 
NewAddNodeShader()163 std::unique_ptr<NodeShader> NewAddNodeShader() {
164   return std::make_unique<Add>();
165 }
166 
167 }  // namespace gl
168 }  // namespace gpu
169 }  // namespace tflite
170