1/* Copyright 2017 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 "tensorflow/compiler/tf2xla/literal_util.h"
17
18#include "tensorflow/compiler/tf2xla/shape_util.h"
19#include "tensorflow/compiler/tf2xla/type_util.h"
20#include "tensorflow/compiler/xla/literal_util.h"
21#include "tensorflow/core/common_runtime/dma_helper.h"
22
23namespace tensorflow {
24
25Status HostTensorToLiteral(const Tensor& host_tensor, xla::Literal* literal) {
26  xla::Shape literal_shape;
27  TF_RETURN_IF_ERROR(TensorShapeToXLAShape(
28      host_tensor.dtype(), host_tensor.shape(), &literal_shape));
29
30  *literal = xla::Literal(literal_shape);
31
32  // memcpy over the payload ...
33  // TODO(phawkins): handle string types.
34  size_t total_bytes = host_tensor.TotalBytes();
35  if (total_bytes > 0) {
36    void* dst_ptr = literal->untyped_data();
37    const void* src_ptr = DMAHelper::base(&host_tensor);
38    memcpy(dst_ptr, src_ptr, total_bytes);
39  }
40  return Status::OK();
41}
42
43Status CopyLiteralToHostTensor(const xla::Literal& literal,
44                               Tensor* host_tensor) {
45  TF_RET_CHECK(xla::ShapeUtil::IsArray(literal.shape()) &&
46               xla::ShapeUtil::ElementsIn(literal.shape()) ==
47                   host_tensor->NumElements());
48  xla::PrimitiveType primitive_type;
49  TF_RETURN_IF_ERROR(
50      DataTypeToPrimitiveType(host_tensor->dtype(), &primitive_type));
51  if (literal.shape().element_type() != primitive_type) {
52    return errors::InvalidArgument(
53        "Cannot convert literal of type ",
54        xla::PrimitiveType_Name(literal.shape().element_type()),
55        " to tensor of type ", DataTypeString(host_tensor->dtype()));
56  }
57  size_t total_bytes = host_tensor->TotalBytes();
58  if (total_bytes > 0) {
59    const void* src_ptr = literal.untyped_data();
60    void* dst_ptr = DMAHelper::base(host_tensor);
61    memcpy(dst_ptr, src_ptr, total_bytes);
62  }
63  return Status::OK();
64}
65
66Status LiteralToHostTensor(const xla::Literal& literal, DataType target_type,
67                           Tensor* host_tensor) {
68  TensorShape shape;
69  TF_RETURN_IF_ERROR(XLAShapeToTensorShape(literal.shape(), &shape));
70  *host_tensor = Tensor(target_type, shape);
71  return CopyLiteralToHostTensor(literal, host_tensor);
72}
73
74}  // namespace tensorflow
75