aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/compiler/xla/tests/local_client_test_base.cc
blob: 49207356e3027cff52a29f962fedbd3593a4925e (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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/* 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/xla/tests/local_client_test_base.h"

#include <vector>

#define EIGEN_USE_THREADS

#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/map_util.h"
#include "tensorflow/compiler/xla/ptr_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/test_helpers.h"
#include "tensorflow/core/common_runtime/eigen_thread_pool.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/platform/cpu_info.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/logging.h"

namespace xla {

/* static */ TestAllocator* LocalClientTestBase::allocator_;

StatusOr<perftools::gputools::DeviceMemoryBase> TestAllocator::Allocate(
    int device_ordinal, uint64 size, bool retry_on_failure) {
  VLOG(2) << "Allocate(" << device_ordinal << ", " << size << ")";
  {
    tensorflow::mutex_lock lock(count_mutex_);
    allocation_count_++;
    device_allocation_count_[device_ordinal]++;
  }
  return StreamExecutorMemoryAllocator::Allocate(device_ordinal, size);
}

tensorflow::Status TestAllocator::Deallocate(
    int device_ordinal, perftools::gputools::DeviceMemoryBase* mem) {
  VLOG(2) << "Deallocate(" << device_ordinal << ")";
  {
    tensorflow::mutex_lock lock(count_mutex_);
    deallocation_count_++;
    device_deallocation_count_[device_ordinal]++;
  }
  return StreamExecutorMemoryAllocator::Deallocate(device_ordinal, mem);
}

int64 TestAllocator::allocation_count() const {
  tensorflow::mutex_lock lock(count_mutex_);
  return allocation_count_;
}

int64 TestAllocator::allocation_count(int device_ordinal) const {
  tensorflow::mutex_lock lock(count_mutex_);
  auto it = device_allocation_count_.find(device_ordinal);
  if (it == device_allocation_count_.end()) {
    return 0;
  } else {
    return it->second;
  }
}

int64 TestAllocator::deallocation_count() const {
  tensorflow::mutex_lock lock(count_mutex_);
  return deallocation_count_;
}

int64 TestAllocator::deallocation_count(int device_ordinal) const {
  tensorflow::mutex_lock lock(count_mutex_);
  auto it = device_deallocation_count_.find(device_ordinal);
  if (it == device_deallocation_count_.end()) {
    return 0;
  } else {
    return it->second;
  }
}

/* static */ TestAllocator* LocalClientTestBase::GetOrCreateAllocator(
    perftools::gputools::Platform* platform) {
  if (allocator_ == nullptr) {
    allocator_ = new TestAllocator(
        platform == nullptr ? PlatformUtil::GetDefaultPlatform().ValueOrDie()
                            : platform);
  }
  return allocator_;
}

// Define this in .cc file to avoid having to include eigen or forward declare
// these types in the header.
struct LocalClientTestBase::EigenThreadPoolWrapper {
  explicit EigenThreadPoolWrapper()
      : pool(new tensorflow::thread::ThreadPool(
            tensorflow::Env::Default(), "XLAEigenTest", /*num_threads=*/2)),
        wrapper(new tensorflow::EigenThreadPoolWrapper(pool.get())),
        device(new Eigen::ThreadPoolDevice(wrapper.get(),
                                           wrapper->NumThreads())) {}

  std::unique_ptr<tensorflow::thread::ThreadPool> pool;
  std::unique_ptr<tensorflow::EigenThreadPoolWrapper> wrapper;
  std::unique_ptr<Eigen::ThreadPoolDevice> device;
};

LocalClientTestBase::LocalClientTestBase(
    perftools::gputools::Platform* platform)
    : local_client_(
          ClientLibrary::GetOrCreateLocalClient(platform).ValueOrDie()),
      thread_pool_wrapper_(new EigenThreadPoolWrapper()) {
  stream_executor_ = PlatformUtil::GetStreamExecutors(local_client_->platform())
                         .ValueOrDie()[local_client_->default_device_ordinal()];
  transfer_manager_ =
      TransferManager::GetForPlatform(local_client_->platform()).ValueOrDie();
}

LocalClientTestBase::~LocalClientTestBase() {}

std::unique_ptr<ScopedShapedBuffer>
LocalClientTestBase::LiteralToScopedShapedBuffer(const Literal& literal) {
  return LiteralToScopedShapedBuffer(literal,
                                     local_client_->default_device_ordinal());
}

std::unique_ptr<ScopedShapedBuffer>
LocalClientTestBase::LiteralToScopedShapedBuffer(const Literal& literal,
                                                 int device_ordinal) {
  CHECK(!ShapeUtil::IsTuple(literal.shape()));
  auto scoped_buffer =
      ScopedShapedBuffer::MakeScopedShapedBuffer(
          literal.shape(), GetOrCreateAllocator(local_client_->platform()),
          device_ordinal)
          .ConsumeValueOrDie();
  // The creation of the scoped shaped buffer should allocate the buffer.
  CHECK(!scoped_buffer->buffer(/*index=*/{}).is_null() ||
        ShapeUtil::HasZeroElements(literal.shape()));
  TF_CHECK_OK(transfer_manager_->TransferLiteralToDevice(
      stream_executor_, literal, scoped_buffer->mutable_buffer(/*index=*/{})));
  return scoped_buffer;
}

void LocalClientTestBase::CopyShapedBufferToLiteral(
    const ShapedBuffer& shaped_buffer, ShapeIndex* index, Literal* literal) {
  const Shape& shape = ShapeUtil::GetSubshape(shaped_buffer.shape(), *index);
  if (ShapeUtil::IsTuple(shape)) {
    *literal->mutable_shape() = shape;
    for (int i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) {
      Literal* element_literal = literal->add_tuple_literals();
      index->push_back(i);
      CopyShapedBufferToLiteral(shaped_buffer, index, element_literal);
      index->pop_back();
    }
  } else {
    ASSERT_IS_OK(transfer_manager_->TransferLiteralFromDevice(
        stream_executor_, shaped_buffer.buffer(*index), shape, shape, literal));
  }
}

std::unique_ptr<Literal> LocalClientTestBase::ShapedBufferToLiteral(
    const ShapedBuffer& shaped_buffer) {
  auto literal = MakeUnique<Literal>();
  ShapeIndex index;
  CopyShapedBufferToLiteral(shaped_buffer, &index, literal.get());
  return literal;
}

std::unique_ptr<ScopedShapedBuffer>
LocalClientTestBase::ShapedBufferToScopedShapedBuffer(
    std::unique_ptr<ShapedBuffer> shaped_buffer,
    DeviceMemoryAllocator* allocator) {
  std::unique_ptr<ScopedShapedBuffer> scoped_buffer =
      ScopedShapedBuffer::MakeScopedShapedBuffer(
          shaped_buffer->shape(), allocator, shaped_buffer->device_ordinal())
          .ConsumeValueOrDie();
  // Deallocate the existing DeviceMemoryBase values in the newly created scoped
  // buffer and replace them with the values from the shaped buffer.
  for (perftools::gputools::DeviceMemoryBase& memory_base :
       *scoped_buffer->mutable_buffers()) {
    TF_CHECK_OK(
        allocator->Deallocate(shaped_buffer->device_ordinal(), &memory_base));
  }
  *scoped_buffer->mutable_buffers() = shaped_buffer->buffers();

  scoped_buffer->mutable_shape_index_to_buffer_entry()->ForEachMutableElement(
      [&shaped_buffer](const ShapeIndex& index, size_t* buffer_entry) {
        if (ShapeUtil::IsLeafIndex(shaped_buffer->shape(), index)) {
          *buffer_entry =
              shaped_buffer->shape_index_to_buffer_entry().element(index);
        }
      });
  return scoped_buffer;
}

ExecutableBuildOptions LocalClientTestBase::DefaultExecutableBuildOptions()
    const {
  return ExecutableBuildOptions();
}

ExecutableRunOptions LocalClientTestBase::DefaultExecutableRunOptions() const {
  ExecutableRunOptions run_options;
  run_options.set_inter_op_thread_pool(
      local_client_->backend().inter_op_thread_pool());
  run_options.set_intra_op_thread_pool(thread_pool_wrapper_->device.get());
  run_options.set_allocator(GetOrCreateAllocator(local_client_->platform()));
  return run_options;
}

std::unique_ptr<ScopedShapedBuffer> LocalClientTestBase::ExecuteLocallyOrDie(
    const Computation& computation,
    tensorflow::gtl::ArraySlice<const ShapedBuffer*> arguments) {
  return ExecuteLocally(computation, arguments, DefaultExecutableBuildOptions(),
                        DefaultExecutableRunOptions())
      .ConsumeValueOrDie();
}

std::unique_ptr<ScopedShapedBuffer> LocalClientTestBase::ExecuteLocallyOrDie(
    const Computation& computation,
    tensorflow::gtl::ArraySlice<const ShapedBuffer*> arguments,
    const ExecutableBuildOptions& build_options,
    const ExecutableRunOptions& run_options) {
  return ExecuteLocally(computation, arguments, build_options, run_options)
      .ConsumeValueOrDie();
}

StatusOr<std::unique_ptr<ScopedShapedBuffer>>
LocalClientTestBase::ExecuteLocally(
    const Computation& computation,
    tensorflow::gtl::ArraySlice<const ShapedBuffer*> arguments) {
  return ExecuteLocally(computation, arguments, DefaultExecutableBuildOptions(),
                        DefaultExecutableRunOptions());
}

StatusOr<std::unique_ptr<ScopedShapedBuffer>>
LocalClientTestBase::ExecuteLocally(
    const Computation& computation,
    tensorflow::gtl::ArraySlice<const ShapedBuffer*> arguments,
    const ExecutableBuildOptions& build_options,
    const ExecutableRunOptions& run_options) {
  std::vector<const Shape*> argument_layouts(arguments.size());
  for (int i = 0; i < arguments.size(); ++i) {
    argument_layouts[i] = &arguments[i]->shape();
  }
  TF_ASSIGN_OR_RETURN(
      std::unique_ptr<LocalExecutable> executable,
      local_client_->Compile(computation, argument_layouts, build_options));
  TF_ASSIGN_OR_RETURN(std::unique_ptr<ShapedBuffer> buffer,
                      executable->Run(arguments, run_options));
  return ShapedBufferToScopedShapedBuffer(std::move(buffer),
                                          run_options.allocator());
}

}  // namespace xla