1 /* Copyright 2020 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/mean.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
28 namespace tflite {
29 namespace gpu {
30 namespace gl {
31 namespace {
32
33 class Mean : public NodeShader {
34 public:
GenerateCode(const GenerationContext & ctx,GeneratedCode * generated_code) const35 Status GenerateCode(const GenerationContext& ctx,
36 GeneratedCode* generated_code) const final {
37 auto attr = absl::any_cast<MeanAttributes>(ctx.node->operation.attributes);
38 if (attr.dims != std::set<Axis>({Axis::HEIGHT, Axis::WIDTH})) {
39 return InvalidArgumentError(
40 "Mean calculation is supported only for height and width.");
41 }
42
43 auto input = ctx.graph->FindInputs(ctx.node->id)[0];
44
45 std::vector<Variable> parameters = {
46 {"input_data_0_h", input->tensor.shape.h},
47 {"input_data_0_w", input->tensor.shape.w}};
48
49 std::string source = R"(
50 vec4 sum = vec4(0.0);
51 float size = float($input_data_0_w$ * $input_data_0_h$);
52 for (int w = 0; w < $input_data_0_w$; w++) {
53 for (int h = 0; h < $input_data_0_h$; h++) {
54 sum += $input_data_0[w, h, gid.z]$;
55 }
56 }
57 value_0 = sum / size;
58 )";
59 *generated_code = {
60 /*parameters=*/std::move(parameters),
61 /*objects=*/{},
62 /*shared_variables=*/{},
63 /*workload=*/uint3(),
64 /*workgroup=*/uint3(1, 1, 4),
65 /*source_code=*/std::move(source),
66 /*input=*/IOStructure::ONLY_DEFINITIONS,
67 /*output=*/IOStructure::AUTO,
68 };
69 return OkStatus();
70 }
71 };
72
73 } // namespace
74
NewMeanNodeShader()75 std::unique_ptr<NodeShader> NewMeanNodeShader() {
76 return absl::make_unique<Mean>();
77 }
78
79 } // namespace gl
80 } // namespace gpu
81 } // namespace tflite
82