Skip to content

Commit cd4f584

Browse files
Minimal support for running OpsTest on GPU, using CUDA unified memory.
PiperOrigin-RevId: 169897567
1 parent c4873e2 commit cd4f584

4 files changed

Lines changed: 151 additions & 55 deletions

File tree

‎tensorflow/core/BUILD‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2109,6 +2109,7 @@ GPU_RUNTIME_HEADERS = [
21092109
"common_runtime/gpu/gpu_debug_allocator.h",
21102110
"common_runtime/gpu/gpu_device.h",
21112111
"common_runtime/gpu/gpu_init.h",
2112+
"common_runtime/gpu/gpu_managed_allocator.h",
21122113
"common_runtime/gpu/gpu_stream_util.h",
21132114
"common_runtime/gpu/gpu_util.h",
21142115
"common_runtime/gpu/pool_allocator.h",
@@ -2123,6 +2124,7 @@ tf_cuda_library(
21232124
"common_runtime/gpu/gpu_debug_allocator.cc",
21242125
"common_runtime/gpu/gpu_device.cc",
21252126
"common_runtime/gpu/gpu_device_factory.cc",
2127+
"common_runtime/gpu/gpu_managed_allocator.cc",
21262128
"common_runtime/gpu/gpu_stream_util.cc",
21272129
"common_runtime/gpu/gpu_util.cc",
21282130
"common_runtime/gpu/gpu_util_platform_specific.cc",
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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/core/common_runtime/gpu/gpu_managed_allocator.h"
17+
18+
#ifdef GOOGLE_CUDA
19+
#include "cuda/include/cuda.h"
20+
#endif // GOOGLE_CUDA
21+
22+
namespace tensorflow {
23+
24+
void* GpuManagedAllocator::AllocateRaw(size_t alignment, size_t num_bytes) {
25+
#ifdef GOOGLE_CUDA
26+
CUdeviceptr ptr = 0;
27+
CHECK_EQ(cuMemAllocManaged(&ptr, num_bytes, CU_MEM_ATTACH_GLOBAL),
28+
CUDA_SUCCESS);
29+
CHECK(!(ptr & (alignment - 1)));
30+
return reinterpret_cast<void*>(ptr);
31+
#else
32+
return nullptr;
33+
#endif
34+
}
35+
36+
void GpuManagedAllocator::DeallocateRaw(void* ptr) {
37+
#ifdef GOOGLE_CUDA
38+
CHECK_EQ(cuMemFree(reinterpret_cast<CUdeviceptr>(ptr)), CUDA_SUCCESS);
39+
#endif
40+
}
41+
42+
} // namespace tensorflow
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
#ifndef THIRD_PARTY_TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_MANAGED_ALLOCATOR_H_
17+
#define THIRD_PARTY_TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_MANAGED_ALLOCATOR_H_
18+
19+
#include "tensorflow/core/framework/allocator.h"
20+
21+
namespace tensorflow {
22+
23+
// An allocator for CUDA unified memory. Memory allocated with this allocator
24+
// can be accessed from both host and device. CUDA transparently migrates dirty
25+
// pages, which can be slow. Therefore, this allocator is intended for
26+
// convenience in functional tests only.
27+
class GpuManagedAllocator : public Allocator {
28+
public:
29+
string Name() override { return "GpuManagedAllocator"; }
30+
void* AllocateRaw(size_t alignment, size_t num_bytes) override;
31+
void DeallocateRaw(void* ptr) override;
32+
};
33+
34+
} // namespace tensorflow
35+
36+
#endif // THIRD_PARTY_TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_MANAGED_ALLOCATOR_H_

‎tensorflow/core/kernels/ops_testutil.h‎

Lines changed: 71 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,12 @@ limitations under the License.
4646
#include "tensorflow/core/public/version.h"
4747
#include "tensorflow/core/util/tensor_slice_reader_cache.h"
4848

49-
namespace tensorflow {
49+
#ifdef GOOGLE_CUDA
50+
#include "cuda/include/cuda.h"
51+
#include "tensorflow/core/common_runtime/gpu/gpu_managed_allocator.h"
52+
#endif
5053

54+
namespace tensorflow {
5155
namespace test {
5256

5357
inline void SetOutputAttrs(OpKernelContext::Params* params,
@@ -71,14 +75,16 @@ inline void SetOutputAttrs(OpKernelContext::Params* params,
7175
// to use the BrainClient interface.
7276
class OpsTestBase : public ::testing::Test {
7377
public:
74-
OpsTestBase() : device_type_(DEVICE_CPU) {
75-
device_.reset(
76-
DeviceFactory::NewDevice("CPU", {}, "/job:a/replica:0/task:0"));
78+
OpsTestBase()
79+
: device_(DeviceFactory::NewDevice("CPU", {}, "/job:a/replica:0/task:0")),
80+
device_type_(DEVICE_CPU) {
7781
CHECK(device_.get()) << "Could not create CPU device";
82+
allocator_ = device_->GetAllocator(AllocatorAttributes());
7883
}
7984

8085
~OpsTestBase() override {
8186
gtl::STLDeleteElements(&tensors_);
87+
gtl::STLDeleteElements(&managed_outputs_);
8288
context_.reset(nullptr);
8389
params_.reset(nullptr);
8490
}
@@ -89,6 +95,18 @@ class OpsTestBase : public ::testing::Test {
8995
CHECK(device_.get()) << "No device provided";
9096
device_type_ = device_type;
9197
device_ = std::move(device);
98+
#ifdef GOOGLE_CUDA
99+
if (device_type == DEVICE_GPU) {
100+
managed_allocator_.reset(new GpuManagedAllocator());
101+
allocator_ = managed_allocator_.get();
102+
} else {
103+
managed_allocator_.reset();
104+
allocator_ = device_->GetAllocator(AllocatorAttributes());
105+
}
106+
#else
107+
CHECK_NE(device_type, DEVICE_GPU)
108+
<< "Requesting GPU on binary compiled without GOOGLE_CUDA.";
109+
#endif
92110
}
93111

94112
void set_node_def(const NodeDef& node_def) { node_def_.CopyFrom(node_def); }
@@ -118,64 +136,22 @@ class OpsTestBase : public ::testing::Test {
118136
// TODO(vrv): Replace with something like a BrainClient Feed.
119137
template <typename T>
120138
void AddInput(const TensorShape& shape, std::function<T(int)> input_mapping) {
121-
CHECK_GT(input_types_.size(), inputs_.size())
122-
<< "Adding more inputs than types; perhaps you need to call MakeOp";
123-
bool is_ref = IsRefType(input_types_[inputs_.size()]);
124-
Tensor* input = new Tensor(device_->GetAllocator(AllocatorAttributes()),
125-
DataTypeToEnum<T>::v(), shape);
126-
test::FillFn(input, input_mapping);
127-
tensors_.push_back(input);
128-
if (is_ref) {
129-
CHECK_EQ(RemoveRefType(input_types_[inputs_.size()]),
130-
DataTypeToEnum<T>::v());
131-
inputs_.push_back({&lock_for_refs_, input});
132-
} else {
133-
CHECK_EQ(input_types_[inputs_.size()], DataTypeToEnum<T>::v());
134-
inputs_.push_back({nullptr, input});
135-
}
139+
test::FillFn(AddInput(DataTypeToEnum<T>::v(), shape), input_mapping);
136140
}
137141

138142
// Like AddInput but takes in an explicit arrayslice of data.
139143
template <typename T>
140144
void AddInputFromArray(const TensorShape& shape,
141145
const gtl::ArraySlice<T>& data) {
142-
CHECK_GT(input_types_.size(), inputs_.size())
143-
<< "Adding more inputs than types; perhaps you need to call MakeOp";
144-
bool is_ref = IsRefType(input_types_[inputs_.size()]);
145-
Tensor* input = new Tensor(device_->GetAllocator(AllocatorAttributes()),
146-
DataTypeToEnum<T>::v(), shape);
147-
test::FillValues<T>(input, data);
148-
tensors_.push_back(input);
149-
if (is_ref) {
150-
CHECK_EQ(RemoveRefType(input_types_[inputs_.size()]),
151-
DataTypeToEnum<T>::v());
152-
inputs_.push_back({&lock_for_refs_, input});
153-
} else {
154-
CHECK_EQ(input_types_[inputs_.size()], DataTypeToEnum<T>::v());
155-
inputs_.push_back({nullptr, input});
156-
}
146+
test::FillValues<T>(AddInput(DataTypeToEnum<T>::v(), shape), data);
157147
}
158148

159149
// Convenience function to add an input and populate it with the elements from
160150
// an initializer list converting the types as needed.
161151
template <typename T, typename SrcType>
162152
void AddInputFromList(const TensorShape& shape,
163153
std::initializer_list<SrcType> data) {
164-
CHECK_GT(input_types_.size(), inputs_.size())
165-
<< "Adding more inputs than types; perhaps you need to call MakeOp";
166-
bool is_ref = IsRefType(input_types_[inputs_.size()]);
167-
Tensor* input = new Tensor(device_->GetAllocator(AllocatorAttributes()),
168-
DataTypeToEnum<T>::v(), shape);
169-
test::FillValues<T>(input, data);
170-
tensors_.push_back(input);
171-
if (is_ref) {
172-
CHECK_EQ(RemoveRefType(input_types_[inputs_.size()]),
173-
DataTypeToEnum<T>::v());
174-
inputs_.push_back({&lock_for_refs_, input});
175-
} else {
176-
CHECK_EQ(input_types_[inputs_.size()], DataTypeToEnum<T>::v());
177-
inputs_.push_back({nullptr, input});
178-
}
154+
test::FillValues<T>(AddInput(DataTypeToEnum<T>::v(), shape), data);
179155
}
180156

181157
// Adds a Resource type as input. If <container> is empty, uses the default
@@ -197,8 +173,7 @@ class OpsTestBase : public ::testing::Test {
197173
handle.set_name(name);
198174
handle.set_hash_code(type_index.hash_code());
199175
handle.set_maybe_type_name(type_index.name());
200-
Tensor* input = new Tensor(device_->GetAllocator(AllocatorAttributes()),
201-
DT_RESOURCE, TensorShape({}));
176+
Tensor* input = new Tensor(allocator(), DT_RESOURCE, TensorShape({}));
202177
input->scalar<ResourceHandle>()() = handle;
203178
tensors_.push_back(input);
204179
inputs_.push_back({nullptr, input});
@@ -248,17 +223,54 @@ class OpsTestBase : public ::testing::Test {
248223
// REQUIRES: 0 <= output_index < context_->num_outputs()
249224
Tensor* GetOutput(int output_index) {
250225
CHECK_LT(output_index, context_->num_outputs());
251-
return context_->mutable_output(output_index);
226+
Tensor* output = context_->mutable_output(output_index);
227+
#ifdef GOOGLE_CUDA
228+
if (device_type_ == DEVICE_GPU) {
229+
managed_outputs_.resize(context_->num_outputs());
230+
// Copy the output tensor to managed memory if we haven't done so.
231+
if (!managed_outputs_[output_index]) {
232+
Tensor* managed_output =
233+
new Tensor(allocator(), output->dtype(), output->shape());
234+
auto src = output->tensor_data();
235+
auto dst = managed_output->tensor_data();
236+
CHECK_EQ(
237+
cuMemcpyDtoD(reinterpret_cast<CUdeviceptr>(dst.data()),
238+
reinterpret_cast<CUdeviceptr>(src.data()), src.size()),
239+
CUDA_SUCCESS);
240+
CHECK_EQ(cuCtxSynchronize(), CUDA_SUCCESS);
241+
managed_outputs_[output_index] = managed_output;
242+
}
243+
output = managed_outputs_[output_index];
244+
}
245+
#endif
246+
return output;
252247
}
253248

254-
Allocator* allocator() {
255-
return device_->GetAllocator(AllocatorAttributes());
256-
}
249+
Allocator* allocator() { return allocator_; }
257250

258251
const DataTypeVector& output_types() const { return kernel_->output_types(); }
259252

253+
private:
254+
Tensor* AddInput(DataType dtype, const TensorShape& shape) {
255+
CHECK_GT(input_types_.size(), inputs_.size())
256+
<< "Adding more inputs than types; perhaps you need to call MakeOp";
257+
bool is_ref = IsRefType(input_types_[inputs_.size()]);
258+
Tensor* input = new Tensor(allocator(), dtype, shape);
259+
tensors_.push_back(input);
260+
if (is_ref) {
261+
CHECK_EQ(RemoveRefType(input_types_[inputs_.size()]), dtype);
262+
inputs_.push_back({&lock_for_refs_, input});
263+
} else {
264+
CHECK_EQ(input_types_[inputs_.size()], dtype);
265+
inputs_.push_back({nullptr, input});
266+
}
267+
return input;
268+
}
269+
260270
protected:
261271
std::unique_ptr<Device> device_;
272+
// The device allocator, or the managed_allocator_ below if running on GPU.
273+
Allocator* allocator_;
262274

263275
std::unique_ptr<OpKernel> kernel_;
264276
std::unique_ptr<ScopedStepContainer> step_container_;
@@ -271,9 +283,13 @@ class OpsTestBase : public ::testing::Test {
271283
gtl::InlinedVector<TensorValue, 4> inputs_;
272284
// Owns Tensors.
273285
std::vector<Tensor*> tensors_;
286+
// Copies of the outputs in unified memory (host and device accessible).
287+
std::vector<Tensor*> managed_outputs_;
274288

275289
std::unique_ptr<OpKernelContext::Params> params_;
276290
std::unique_ptr<OpKernelContext> context_;
291+
// Unified memory allocator, only used when running on GPU.
292+
std::unique_ptr<Allocator> managed_allocator_;
277293

278294
private:
279295
TF_DISALLOW_COPY_AND_ASSIGN(OpsTestBase);

0 commit comments

Comments
 (0)