2 * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "kernels/If.h"
21 namespace luci_interpreter
26 static std::vector<const Tensor *> joinInputs(const Tensor *cond,
27 const std::vector<const Tensor *> &inputs)
29 std::vector<const Tensor *> result{cond};
30 result.insert(result.cend(), inputs.cbegin(), inputs.cend());
34 If::If(const Tensor *cond, const std::vector<const Tensor *> &inputs, std::vector<Tensor *> outputs,
35 RuntimeGraph *then_graph, RuntimeGraph *else_graph)
36 : Kernel(joinInputs(cond, inputs), std::move(outputs)), _then_graph(then_graph),
37 _else_graph(else_graph)
43 assert(cond()->element_type() == DataType::BOOL);
44 assert(cond()->shape().num_elements() == 1);
46 for (RuntimeGraph *graph : {_then_graph, _else_graph})
49 assert(graph->getInputTensors().size() == getInputTensors().size() - 1);
50 assert(graph->getOutputTensors().size() == getOutputTensors().size());
54 void If::execute() const
56 const bool cond_value = cond()->data<bool>()[0];
58 RuntimeGraph *active_graph = cond_value ? _then_graph : _else_graph;
59 const auto &graph_inputs = active_graph->getInputTensors();
60 const auto &graph_outputs = active_graph->getOutputTensors();
62 // Copy kernel inputs to active graph inputs.
63 for (size_t i = 0; i < getInputTensors().size() - 1; ++i)
65 assert(graph_inputs[i]->element_type() == input(i)->element_type());
66 graph_inputs[i]->resize(input(i)->shape());
68 const int32_t num_elements = input(i)->shape().num_elements();
69 const std::size_t element_size = getDataTypeSize(input(i)->element_type());
70 std::memcpy(graph_inputs[i]->data<void>(), input(i)->data<void>(), num_elements * element_size);
73 active_graph->execute();
75 // Copy graph outputs to kernel outputs.
76 for (size_t i = 0; i < getOutputTensors().size(); ++i)
78 assert(graph_outputs[i]->element_type() == output(i)->element_type());
79 output(i)->resize(graph_outputs[i]->shape());
81 const int32_t num_elements = output(i)->shape().num_elements();
82 const std::size_t element_size = getDataTypeSize(output(i)->element_type());
83 std::memcpy(output(i)->data<void>(), graph_outputs[i]->data<void>(),
84 num_elements * element_size);
88 } // namespace kernels
89 } // namespace luci_interpreter