xref: /aosp_15_r20/external/tensorflow/tensorflow/core/kernels/composite_tensor_ops.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
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/core/framework/op.h"
17 #include "tensorflow/core/framework/op_kernel.h"
18 #include "tensorflow/core/framework/variant.h"
19 #include "tensorflow/core/framework/variant_encode_decode.h"
20 #include "tensorflow/core/kernels/composite_tensor_variant.h"
21 #include "tensorflow/core/platform/errors.h"
22 #include "tensorflow/core/protobuf/composite_tensor_variant.pb.h"
23 #include "tensorflow/core/protobuf/struct.pb.h"
24 
25 namespace tensorflow {
26 
27 class CompositeTensorVariantFromComponents : public OpKernel {
28  public:
CompositeTensorVariantFromComponents(OpKernelConstruction * context)29   explicit CompositeTensorVariantFromComponents(OpKernelConstruction* context)
30       : OpKernel(context) {
31     string type_spec_string;
32     OP_REQUIRES_OK(context, context->GetAttr("metadata", &type_spec_string));
33     OP_REQUIRES(context, metadata_.ParseFromString(type_spec_string),
34                 errors::InvalidArgument("Error parsing metadata"));
35   }
36 
Compute(OpKernelContext * context)37   void Compute(OpKernelContext* context) override {
38     OpInputList components_in;
39     OP_REQUIRES_OK(context, context->input_list("components", &components_in));
40 
41     Tensor* encoded;
42     OP_REQUIRES_OK(context,
43                    context->allocate_output(0, TensorShape({}), &encoded));
44 
45     std::vector<Tensor> components{components_in.begin(), components_in.end()};
46     encoded->flat<Variant>()(0) =
47         CompositeTensorVariant(metadata_, absl::MakeSpan(components));
48   }
49 
50  private:
51   CompositeTensorVariantMetadata metadata_;
52 };
53 
54 class CompositeTensorVariantToComponents : public OpKernel {
55  public:
CompositeTensorVariantToComponents(OpKernelConstruction * context)56   explicit CompositeTensorVariantToComponents(OpKernelConstruction* context)
57       : OpKernel(context) {
58     string type_spec_string;
59     OP_REQUIRES_OK(context, context->GetAttr("metadata", &type_spec_string));
60     OP_REQUIRES(context, metadata_.ParseFromString(type_spec_string),
61                 errors::InvalidArgument("Error parsing `metadata`"));
62 
63     OP_REQUIRES_OK(context,
64                    context->GetAttr("Tcomponents", &component_dtypes_));
65   }
66 
Compute(OpKernelContext * context)67   void Compute(OpKernelContext* context) override {
68     Tensor encoded_t = context->input(0);
69     auto* encoded = encoded_t.flat<Variant>()(0).get<CompositeTensorVariant>();
70 
71     // Check that the encoded TypeSpec is compatible with the expected TypeSpec.
72     // For now, we just check that the class matches.
73     //
74     // TODO(b/173744905): Update this to do a generic compatibility check. This
75     // would require replacing the current design, where Python subclasses of
76     // TypeSpec can override is_compatible, with a design where compatibility
77     // can be deterministically determined from the metadata.
78     auto expected_class = metadata_.type_spec_proto().type_spec_class();
79     auto actual_class = encoded->metadata().type_spec_proto().type_spec_class();
80     OP_REQUIRES(
81         context, expected_class == actual_class,
82         errors::InvalidArgument(
83             "Expected a ", TypeSpecProto::TypeSpecClass_Name(expected_class),
84             " (based on `type_spec`), but `encoded` contains a ",
85             TypeSpecProto::TypeSpecClass_Name(actual_class)));
86 
87     // Extract the component tensors.
88     OpOutputList components;
89     OP_REQUIRES_OK(context, context->output_list("components", &components));
90     int num_components = encoded->flat_components().size();
91 
92     OP_REQUIRES(context, component_dtypes_.size() == num_components,
93                 errors::InvalidArgument("Encoded value has ", num_components,
94                                         " tensor components; expected ",
95                                         component_dtypes_.size(),
96                                         " components based on type_spec"));
97 
98     for (int i = 0; i < component_dtypes_.size(); i++) {
99       const Tensor& component = encoded->flat_components()[i];
100       OP_REQUIRES(context, component_dtypes_[i] == component.dtype(),
101                   errors::InvalidArgument("Tensor component ", i, " had dtype ",
102                                           DataType_Name(component.dtype()),
103                                           "; expected dtype ",
104                                           DataType_Name(component_dtypes_[i])));
105       components.set(i, component);
106     }
107   }
108 
109  private:
110   CompositeTensorVariantMetadata metadata_;
111   std::vector<DataType> component_dtypes_;
112 };
113 
114 REGISTER_KERNEL_BUILDER(
115     Name("CompositeTensorVariantToComponents").Device(DEVICE_CPU),
116     CompositeTensorVariantToComponents);
117 REGISTER_KERNEL_BUILDER(
118     Name("CompositeTensorVariantFromComponents").Device(DEVICE_CPU),
119     CompositeTensorVariantFromComponents);
120 
121 }  // namespace tensorflow
122