Home | History | Annotate | Download | only in tf2xla
      1 /* Copyright 2017 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/compiler/tf2xla/shape_util.h"
     17 
     18 #include <numeric>
     19 
     20 #include "tensorflow/compiler/tf2xla/type_util.h"
     21 #include "tensorflow/compiler/xla/shape_util.h"
     22 #include "tensorflow/core/lib/core/status.h"
     23 
     24 namespace tensorflow {
     25 
     26 // Convert an XLA Shape into the equivalent TensorFlow shape.
     27 Status XLAShapeToTensorShape(const xla::Shape& shape,
     28                              TensorShape* tensor_shape) {
     29   if (xla::ShapeUtil::IsTuple(shape)) {
     30     return errors::InvalidArgument("XLA shape ",
     31                                    xla::ShapeUtil::HumanString(shape),
     32                                    " cannot be converted to a TensorShape");
     33   }
     34   *tensor_shape = TensorShape();
     35   for (int i = 0; i < xla::ShapeUtil::Rank(shape); ++i) {
     36     tensor_shape->AddDim(shape.dimensions(i));
     37   }
     38   return Status::OK();
     39 }
     40 
     41 // Convert a TensorShape into the equivalent XLA Shape proto.
     42 Status TensorShapeToXLAShape(DataType dtype, const TensorShape& tensor_shape,
     43                              xla::Shape* shape) {
     44   int rank = tensor_shape.dims();
     45   std::vector<int64> dimensions(rank);
     46   std::vector<int64> layout(rank);
     47   for (int d = 0; d < rank; ++d) {
     48     dimensions[d] = tensor_shape.dim_size(d);
     49   }
     50   // XLA uses minor-to-major; Tensorflow uses major-to-minor.
     51   std::iota(layout.rbegin(), layout.rend(), 0);
     52 
     53   xla::PrimitiveType type;
     54   TF_RETURN_IF_ERROR(DataTypeToPrimitiveType(dtype, &type));
     55 
     56   *shape = xla::ShapeUtil::MakeShapeWithLayout(type, dimensions, layout);
     57   return Status::OK();
     58 }
     59 
     60 }  // namespace tensorflow
     61