xref: /aosp_15_r20/external/tensorflow/tensorflow/core/kernels/uniform_quant_ops/tensor_utils.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2022 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 #include "tensorflow/core/kernels/uniform_quant_ops/tensor_utils.h"
16 
17 namespace tensorflow {
18 
19 using tensorflow::errors::InvalidArgument;
20 
QuantizationAxisAndShapeValid(const TensorShape & data_shape,const TensorShape & scales_shape,const TensorShape & zero_points_shape,int quantization_axis)21 Status QuantizationAxisAndShapeValid(const TensorShape& data_shape,
22                                      const TensorShape& scales_shape,
23                                      const TensorShape& zero_points_shape,
24                                      int quantization_axis) {
25   if (!scales_shape.IsSameSize(zero_points_shape)) {
26     return InvalidArgument(
27         "scales and zero_points shape must be same, but given scales shape ",
28         scales_shape.DebugString(), " and zero_points shape ",
29         zero_points_shape.DebugString());
30   }
31   if (quantization_axis < -1 || quantization_axis >= data_shape.dims()) {
32     return InvalidArgument(
33         "quantization_axis must be -1 or in range [0, input.rank), but given ",
34         quantization_axis);
35   }
36 
37   if (quantization_axis == -1) {
38     if (scales_shape.dims() != 0) {
39       return InvalidArgument(
40           "If quantization_axis is -1, scales and zero_points must be scalar "
41           "tensors, but given scales shape ",
42           scales_shape.DebugString(), " and zero_points shape ",
43           zero_points_shape.DebugString());
44     }
45   } else {
46     if (!(scales_shape.dims() == 1 &&
47           scales_shape.dim_size(0) == data_shape.dim_size(quantization_axis))) {
48       return InvalidArgument(
49           "If quantization_axis is not -1, scales and zero_points must be a "
50           "tensor of rank 1 and the size must be equal to the "
51           "input.dim_size(quantization_axis), but given quantization_axis ",
52           quantization_axis, ", scales shape ", scales_shape.DebugString(),
53           " and zero_points shape ", zero_points_shape.DebugString());
54     }
55   }
56   return OkStatus();
57 }
58 
59 }  // namespace tensorflow
60