aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/compiler/jit/xla_device_context.cc
blob: 250960d39586af5101342dfecc0614d53cd5bc2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/jit/xla_device_context.h"

#include "tensorflow/compiler/tf2xla/literal_util.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/core/common_runtime/dma_helper.h"

namespace tensorflow {

// The contents of tensors allocated by XlaDeviceAllocator.
struct XlaGlobalData {
  mutable mutex mu;
  // May be nullptr if there is no xla::GlobalData backing this Tensor.
  std::shared_ptr<xla::GlobalData> data GUARDED_BY(mu);
};

// The allocator used for Tensors assigned to the XLA device. The allocator
// doesn't actually back Tensors with storage. Instead, each tensor contains
// a XlaGlobalData that wraps XLA-managed storage.
XlaDeviceAllocator::XlaDeviceAllocator() = default;
XlaDeviceAllocator::~XlaDeviceAllocator() = default;

string XlaDeviceAllocator::Name() { return "xla"; }

void* XlaDeviceAllocator::AllocateRaw(size_t alignment, size_t num_bytes) {
  // Regardless of the size requested, always allocate a XlaGlobalData. Respect
  // the aligment request because there is alignment checking even for Tensors
  // whose data is never accessed.
  void* p = port::aligned_malloc(sizeof(XlaGlobalData), alignment);
  VLOG(2) << "Allocated XLA device tensor " << p;
  return new (p) XlaGlobalData();
}

void XlaDeviceAllocator::DeallocateRaw(void* ptr) {
  XlaGlobalData* global_data = reinterpret_cast<XlaGlobalData*>(ptr);
  VLOG(2) << "Deallocated XLA device tensor " << ptr;
  global_data->~XlaGlobalData();
  port::aligned_free(ptr);
}

void XlaDeviceAllocator::GetStats(AllocatorStats* stats) { stats->Clear(); }

// Don't run any constructors or destructors for complex objects,
// since there is no backing store for the tensor to run them
// on. strings are the only complex objects currently stored in
// Tensors. If others are added, this set of overrides must be
// extended to include them.
void XlaDeviceAllocator::RunStringCtor(string* p, size_t n) {}
void XlaDeviceAllocator::RunStringDtor(string* p, size_t n) {}
void XlaDeviceAllocator::RunResourceCtor(ResourceHandle* p, size_t n) {}
void XlaDeviceAllocator::RunResourceDtor(ResourceHandle* p, size_t n) {}

static const XlaGlobalData* CastTensorToXlaGlobalData(const Tensor& tensor) {
  const XlaGlobalData* expression =
      reinterpret_cast<const XlaGlobalData*>(tensor.tensor_data().data());
  return expression;
}

static XlaGlobalData* CastTensorToXlaGlobalData(Tensor* tensor) {
  const XlaGlobalData* expression =
      reinterpret_cast<const XlaGlobalData*>(tensor->tensor_data().data());
  return const_cast<XlaGlobalData*>(expression);
}

XlaTransferManager::XlaTransferManager(xla::Client* client) : client_(client) {}

void XlaTransferManager::CopyCPUTensorToDevice(const Tensor* cpu_tensor,
                                               Device* device,
                                               Tensor* device_tensor,
                                               StatusCallback done) const {
  if (cpu_tensor->NumElements() > 0) {
    VLOG(2) << "CopyCPUTensorToDevice "
            << reinterpret_cast<const void*>(cpu_tensor->tensor_data().data())
            << " " << reinterpret_cast<const void*>(
                          device_tensor->tensor_data().data())
            << cpu_tensor->NumElements();
    xla::Literal literal;
    Status status = HostTensorToLiteral(*cpu_tensor, &literal);
    if (!status.ok()) {
      done(status);
      return;
    }
    auto gd = client_->TransferToServer(literal);
    if (!gd.ok()) {
      done(gd.status());
      return;
    }
    SetTensorGlobalData(
        std::shared_ptr<xla::GlobalData>(std::move(gd.ValueOrDie())),
        device_tensor);
  } else {
    VLOG(2) << "CopyCPUTensorToDevice empty tensor";
  }
  done(Status::OK());
}

void XlaTransferManager::CopyDeviceTensorToCPU(const Tensor* device_tensor,
                                               StringPiece tensor_name,
                                               Device* device,
                                               Tensor* cpu_tensor,
                                               StatusCallback done) {
  if (device_tensor->NumElements() > 0) {
    VLOG(2) << "CopyDeviceTensorToCPU"
            << reinterpret_cast<const void*>(
                   device_tensor->tensor_data().data())
            << " "
            << reinterpret_cast<const void*>(cpu_tensor->tensor_data().data())
            << device_tensor->NumElements();
    std::shared_ptr<xla::GlobalData> global_data =
        GetTensorGlobalData(*device_tensor);

    xla::Shape shape;
    Status status =
        TensorShapeToXLAShape(cpu_tensor->dtype(), cpu_tensor->shape(), &shape);
    if (!status.ok()) {
      done(status);
      return;
    }
    auto result = client_->Transfer(*global_data, &shape);
    if (!result.ok()) {
      done(result.status());
      return;
    }
    const void* src_ptr = xla::LiteralUtil::InternalData(*result.ValueOrDie());
    void* dst_ptr = DMAHelper::base(cpu_tensor);
    size_t total_bytes = cpu_tensor->TotalBytes();
    memcpy(dst_ptr, src_ptr, total_bytes);
  } else {
    VLOG(2) << "CopyDeviceTensorToCPU empty tensor";
  }
  done(Status::OK());
}

std::shared_ptr<xla::GlobalData> XlaTransferManager::GetTensorGlobalData(
    const Tensor& tensor) {
  const XlaGlobalData* data = CastTensorToXlaGlobalData(tensor);
  mutex_lock lock(data->mu);
  CHECK(data->data);
  return data->data;
}

void XlaTransferManager::SetTensorGlobalData(
    std::shared_ptr<xla::GlobalData> global_data, Tensor* tensor) {
  XlaGlobalData* data = CastTensorToXlaGlobalData(tensor);
  mutex_lock lock(data->mu);
  data->data = std::move(global_data);
}

XlaDeviceContext::XlaDeviceContext(xla::Client* client) : manager_(client) {}

void XlaDeviceContext::CopyCPUTensorToDevice(const Tensor* cpu_tensor,
                                             Device* device,
                                             Tensor* device_tensor,
                                             StatusCallback done) const {
  manager_.CopyCPUTensorToDevice(cpu_tensor, device, device_tensor, done);
}

void XlaDeviceContext::CopyDeviceTensorToCPU(const Tensor* device_tensor,
                                             StringPiece tensor_name,
                                             Device* device, Tensor* cpu_tensor,
                                             StatusCallback done) {
  manager_.CopyDeviceTensorToCPU(device_tensor, tensor_name, device, cpu_tensor,
                                 done);
}

}  // namespace tensorflow