1/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16#include <stdint.h>
17
18#include "tensorflow/lite/c/common.h"
19#include "tensorflow/lite/core/subgraph.h"
20#include "tensorflow/lite/experimental/resource/resource_variable.h"
21#include "tensorflow/lite/kernels/internal/tensor.h"
22#include "tensorflow/lite/kernels/kernel_util.h"
23
24namespace tflite {
25namespace ops {
26namespace builtin {
27namespace assign_variable {
28
29constexpr int kInputVariableId = 0;
30constexpr int kInputValue = 1;
31
32TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
33 TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);
34 TF_LITE_ENSURE_EQ(context, NumOutputs(node), 0);
35
36 const TfLiteTensor* input_resource_id_tensor;
37 TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputVariableId,
38 &input_resource_id_tensor));
39 TF_LITE_ENSURE(context, (input_resource_id_tensor->type == kTfLiteResource ||
40 input_resource_id_tensor->type == kTfLiteInt32));
41 TF_LITE_ENSURE_EQ(context, NumElements(input_resource_id_tensor), 1);
42
43 return kTfLiteOk;
44}
45
46TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
47 Subgraph* subgraph = reinterpret_cast<Subgraph*>(context->impl_);
48
49 const TfLiteTensor* input_resource_id_tensor;
50 TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputVariableId,
51 &input_resource_id_tensor));
52 const TfLiteTensor* input_value_tensor;
53 TF_LITE_ENSURE_OK(
54 context, GetInputSafe(context, node, kInputValue, &input_value_tensor));
55
56 int resource_id = input_resource_id_tensor->data.i32[0];
57 auto& resources = subgraph->resources();
58 resource::CreateResourceVariableIfNotAvailable(&resources, resource_id);
59 auto* variable = resource::GetResourceVariable(&resources, resource_id);
60 TF_LITE_ENSURE(context, variable != nullptr);
61 variable->AssignFrom(input_value_tensor);
62
63 return kTfLiteOk;
64}
65
66} // namespace assign_variable
67
68TfLiteRegistration* Register_ASSIGN_VARIABLE() {
69 static TfLiteRegistration r = {nullptr, nullptr, assign_variable::Prepare,
70 assign_variable::Eval};
71 return &r;
72}
73
74} // namespace builtin
75} // namespace ops
76} // namespace tflite
77