Skip to content

Commit b113981

Browse files
smit-hinsutensorflower-gardener
authored andcommitted
Introduce an option to allocate CUDA unified memory
PiperOrigin-RevId: 197490523
1 parent d913a24 commit b113981

12 files changed

Lines changed: 289 additions & 48 deletions

File tree

‎tensorflow/core/BUILD‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ load(
9494
load("//tensorflow:tensorflow.bzl", "tf_cc_test_mkl")
9595
load("//tensorflow:tensorflow.bzl", "tf_cc_test_gpu")
9696
load("//tensorflow:tensorflow.bzl", "tf_cc_tests_gpu")
97+
load("//tensorflow:tensorflow.bzl", "tf_cuda_cc_test")
9798
load("//tensorflow:tensorflow.bzl", "tf_version_info_genrule")
9899
load("//tensorflow:tensorflow.bzl", "tf_cuda_only_cc_test")
99100

@@ -3386,6 +3387,37 @@ tf_cc_tests_gpu(
33863387
],
33873388
)
33883389

3390+
tf_cuda_cc_test(
3391+
name = "gpu_device_unified_memory_test",
3392+
size = "small",
3393+
srcs = [
3394+
"common_runtime/gpu/gpu_device_test.cc",
3395+
],
3396+
linkstatic = tf_kernel_tests_linkstatic(),
3397+
# Runs test on a Guitar cluster that uses P100s to test unified memory
3398+
# allocations.
3399+
tags = tf_cuda_tests_tags() + [
3400+
"guitar",
3401+
"multi_gpu",
3402+
],
3403+
deps = [
3404+
":core_cpu",
3405+
":core_cpu_internal",
3406+
":direct_session",
3407+
":framework",
3408+
":framework_internal",
3409+
":gpu_id",
3410+
":lib",
3411+
":lib_internal",
3412+
":protos_all_cc",
3413+
":test",
3414+
":test_main",
3415+
":testlib",
3416+
"//tensorflow/cc:cc_ops",
3417+
"//tensorflow/core/kernels:ops_util",
3418+
],
3419+
)
3420+
33893421
tf_cc_test_gpu(
33903422
name = "cuda_libdevice_path_test",
33913423
size = "small",

‎tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ GPUBFCAllocator::GPUBFCAllocator(CudaGpuId cuda_gpu_id, size_t total_memory,
3131
const string& name)
3232
: BFCAllocator(
3333
new GPUMemAllocator(
34-
GpuIdUtil::ExecutorForCudaGpuId(cuda_gpu_id).ValueOrDie()),
34+
GpuIdUtil::ExecutorForCudaGpuId(cuda_gpu_id).ValueOrDie(),
35+
gpu_options.per_process_gpu_memory_fraction() > 1.0 ||
36+
gpu_options.experimental().use_unified_memory()),
3537
total_memory, gpu_options.allow_growth(), name) {}
3638

3739
} // namespace tensorflow

‎tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,29 +50,39 @@ class GPUBFCAllocator : public BFCAllocator {
5050
class GPUMemAllocator : public SubAllocator {
5151
public:
5252
// Note: stream_exec cannot be null.
53-
explicit GPUMemAllocator(se::StreamExecutor* stream_exec)
54-
: stream_exec_(stream_exec) {
53+
explicit GPUMemAllocator(se::StreamExecutor* stream_exec,
54+
bool use_unified_memory)
55+
: stream_exec_(stream_exec), use_unified_memory_(use_unified_memory) {
5556
CHECK(stream_exec_ != nullptr);
5657
}
5758
~GPUMemAllocator() override {}
5859

5960
void* Alloc(size_t alignment, size_t num_bytes) override {
6061
void* ptr = nullptr;
6162
if (num_bytes > 0) {
62-
ptr = stream_exec_->AllocateArray<char>(num_bytes).opaque();
63+
if (use_unified_memory_) {
64+
ptr = stream_exec_->UnifiedMemoryAllocate(num_bytes);
65+
} else {
66+
ptr = stream_exec_->AllocateArray<char>(num_bytes).opaque();
67+
}
6368
}
6469
return ptr;
6570
}
6671

6772
void Free(void* ptr, size_t num_bytes) override {
6873
if (ptr != nullptr) {
69-
se::DeviceMemoryBase gpu_ptr(ptr);
70-
stream_exec_->Deallocate(&gpu_ptr);
74+
if (use_unified_memory_) {
75+
stream_exec_->UnifiedMemoryDeallocate(ptr);
76+
} else {
77+
se::DeviceMemoryBase gpu_ptr(ptr);
78+
stream_exec_->Deallocate(&gpu_ptr);
79+
}
7180
}
7281
}
7382

7483
private:
7584
se::StreamExecutor* stream_exec_; // not owned, non-null
85+
const bool use_unified_memory_ = false;
7686

7787
TF_DISALLOW_COPY_AND_ASSIGN(GPUMemAllocator);
7888
};

‎tensorflow/core/common_runtime/gpu/gpu_device.cc‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -809,6 +809,20 @@ Status SingleVirtualDeviceMemoryLimit(const GPUOptions& gpu_options,
809809
int64 allocated_memory = 0;
810810
const double per_process_gpu_memory_fraction =
811811
gpu_options.per_process_gpu_memory_fraction();
812+
if (per_process_gpu_memory_fraction > 1.0 ||
813+
gpu_options.experimental().use_unified_memory()) {
814+
int cc_major = 0, cc_minor = 0;
815+
if (!se->GetDeviceDescription().cuda_compute_capability(&cc_major,
816+
&cc_minor)) {
817+
return errors::Internal("Failed to get compute capability for device.");
818+
}
819+
if (cc_major < 6) {
820+
return errors::Internal(
821+
"Unified memory on GPUs with compute capability lower than 6.0 "
822+
"(pre-Pascal class GPUs) does not support oversubscription.");
823+
}
824+
}
825+
812826
if (per_process_gpu_memory_fraction == 0) {
813827
allocated_memory = available_memory;
814828
const int64 min_system_memory = MinSystemMemory(available_memory);

‎tensorflow/core/common_runtime/gpu/gpu_device_test.cc‎

Lines changed: 109 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,45 @@ limitations under the License.
1717

1818
#include "tensorflow/core/common_runtime/gpu/gpu_device.h"
1919

20+
#include "tensorflow/core/common_runtime/gpu/gpu_id_utils.h"
2021
#include "tensorflow/core/common_runtime/gpu/gpu_init.h"
2122
#include "tensorflow/core/common_runtime/gpu/process_state.h"
2223
#include "tensorflow/core/lib/core/errors.h"
2324
#include "tensorflow/core/lib/core/status.h"
2425
#include "tensorflow/core/lib/core/status_test_util.h"
26+
#include "tensorflow/core/lib/gtl/stl_util.h"
2527
#include "tensorflow/core/platform/test.h"
2628

2729
namespace tensorflow {
30+
namespace {
2831
const char* kDeviceNamePrefix = "/job:localhost/replica:0/task:0";
2932

33+
int64 GetTotalGPUMemory(CudaGpuId gpu_id) {
34+
se::StreamExecutor* se =
35+
GpuIdUtil::ExecutorForCudaGpuId(GPUMachineManager(), gpu_id).ValueOrDie();
36+
37+
int64 total_memory, available_memory;
38+
CHECK(se->DeviceMemoryUsage(&available_memory, &total_memory));
39+
return total_memory;
40+
}
41+
42+
Status GetComputeCapability(CudaGpuId gpu_id, int* cc_major, int* cc_minor) {
43+
se::StreamExecutor* se =
44+
GpuIdUtil::ExecutorForCudaGpuId(GPUMachineManager(), gpu_id).ValueOrDie();
45+
if (!se->GetDeviceDescription().cuda_compute_capability(cc_major, cc_minor)) {
46+
*cc_major = 0;
47+
*cc_minor = 0;
48+
return errors::Internal("Failed to get compute capability for device.");
49+
}
50+
return Status::OK();
51+
}
52+
53+
void ExpectErrorMessageSubstr(const Status& s, StringPiece substr) {
54+
EXPECT_TRUE(str_util::StrContains(s.ToString(), substr))
55+
<< s << ", expected substring " << substr;
56+
}
57+
} // namespace
58+
3059
class GPUDeviceTest : public ::testing::Test {
3160
public:
3261
void TearDown() override { ProcessState::singleton()->TestOnlyReset(); }
@@ -52,11 +81,6 @@ class GPUDeviceTest : public ::testing::Test {
5281
}
5382
return options;
5483
}
55-
56-
static bool StartsWith(const string& lhs, const string& rhs) {
57-
if (rhs.length() > lhs.length()) return false;
58-
return lhs.substr(0, rhs.length()) == rhs;
59-
}
6084
};
6185

6286
TEST_F(GPUDeviceTest, FailedToParseVisibleDeviceList) {
@@ -65,8 +89,7 @@ TEST_F(GPUDeviceTest, FailedToParseVisibleDeviceList) {
6589
Status status = DeviceFactory::GetFactory("GPU")->CreateDevices(
6690
opts, kDeviceNamePrefix, &devices);
6791
EXPECT_EQ(status.code(), error::INVALID_ARGUMENT);
68-
EXPECT_TRUE(StartsWith(status.error_message(), "Could not parse entry"))
69-
<< status;
92+
ExpectErrorMessageSubstr(status, "Could not parse entry");
7093
}
7194

7295
TEST_F(GPUDeviceTest, InvalidGpuId) {
@@ -75,9 +98,8 @@ TEST_F(GPUDeviceTest, InvalidGpuId) {
7598
Status status = DeviceFactory::GetFactory("GPU")->CreateDevices(
7699
opts, kDeviceNamePrefix, &devices);
77100
EXPECT_EQ(status.code(), error::INVALID_ARGUMENT);
78-
EXPECT_TRUE(StartsWith(status.error_message(),
79-
"'visible_device_list' listed an invalid GPU id"))
80-
<< status;
101+
ExpectErrorMessageSubstr(status,
102+
"'visible_device_list' listed an invalid GPU id");
81103
}
82104

83105
TEST_F(GPUDeviceTest, DuplicateEntryInVisibleDeviceList) {
@@ -86,9 +108,8 @@ TEST_F(GPUDeviceTest, DuplicateEntryInVisibleDeviceList) {
86108
Status status = DeviceFactory::GetFactory("GPU")->CreateDevices(
87109
opts, kDeviceNamePrefix, &devices);
88110
EXPECT_EQ(status.code(), error::INVALID_ARGUMENT);
89-
EXPECT_TRUE(StartsWith(status.error_message(),
90-
"visible_device_list contained a duplicate entry"))
91-
<< status;
111+
ExpectErrorMessageSubstr(status,
112+
"visible_device_list contained a duplicate entry");
92113
}
93114

94115
TEST_F(GPUDeviceTest, VirtualDeviceConfigConflictsWithMemoryFractionSettings) {
@@ -97,9 +118,8 @@ TEST_F(GPUDeviceTest, VirtualDeviceConfigConflictsWithMemoryFractionSettings) {
97118
Status status = DeviceFactory::GetFactory("GPU")->CreateDevices(
98119
opts, kDeviceNamePrefix, &devices);
99120
EXPECT_EQ(status.code(), error::INVALID_ARGUMENT);
100-
EXPECT_TRUE(StartsWith(status.error_message(),
101-
"It's invalid to set per_process_gpu_memory_fraction"))
102-
<< status;
121+
ExpectErrorMessageSubstr(
122+
status, "It's invalid to set per_process_gpu_memory_fraction");
103123
}
104124

105125
TEST_F(GPUDeviceTest, GpuDeviceCountTooSmall) {
@@ -110,9 +130,8 @@ TEST_F(GPUDeviceTest, GpuDeviceCountTooSmall) {
110130
Status status = DeviceFactory::GetFactory("GPU")->CreateDevices(
111131
opts, kDeviceNamePrefix, &devices);
112132
EXPECT_EQ(status.code(), error::UNKNOWN);
113-
EXPECT_TRUE(StartsWith(status.error_message(),
114-
"Not enough GPUs to create virtual devices."))
115-
<< status;
133+
ExpectErrorMessageSubstr(status,
134+
"Not enough GPUs to create virtual devices.");
116135
}
117136

118137
TEST_F(GPUDeviceTest, NotEnoughGpuInVisibleDeviceList) {
@@ -123,9 +142,8 @@ TEST_F(GPUDeviceTest, NotEnoughGpuInVisibleDeviceList) {
123142
Status status = DeviceFactory::GetFactory("GPU")->CreateDevices(
124143
opts, kDeviceNamePrefix, &devices);
125144
EXPECT_EQ(status.code(), error::UNKNOWN);
126-
EXPECT_TRUE(StartsWith(status.error_message(),
127-
"Not enough GPUs to create virtual devices."))
128-
<< status;
145+
ExpectErrorMessageSubstr(status,
146+
"Not enough GPUs to create virtual devices.");
129147
}
130148

131149
TEST_F(GPUDeviceTest, VirtualDeviceConfigConflictsWithVisibleDeviceList) {
@@ -138,11 +156,11 @@ TEST_F(GPUDeviceTest, VirtualDeviceConfigConflictsWithVisibleDeviceList) {
138156
Status status = DeviceFactory::GetFactory("GPU")->CreateDevices(
139157
opts, kDeviceNamePrefix, &devices);
140158
EXPECT_EQ(status.code(), error::INVALID_ARGUMENT);
141-
EXPECT_TRUE(StartsWith(status.error_message(),
142-
"The number of GPUs in visible_device_list doesn't "
143-
"match the number of elements in the virtual_devices "
144-
"list."))
145-
<< status;
159+
ExpectErrorMessageSubstr(
160+
status,
161+
"The number of GPUs in visible_device_list doesn't "
162+
"match the number of elements in the virtual_devices "
163+
"list.");
146164
}
147165

148166
TEST_F(GPUDeviceTest, EmptyVirtualDeviceConfig) {
@@ -153,7 +171,7 @@ TEST_F(GPUDeviceTest, EmptyVirtualDeviceConfig) {
153171
opts, kDeviceNamePrefix, &devices));
154172
EXPECT_EQ(1, devices.size());
155173
EXPECT_GE(devices[0]->attributes().memory_limit(), 0);
156-
for (auto d : devices) delete d;
174+
gtl::STLDeleteElements(&devices);
157175
}
158176

159177
TEST_F(GPUDeviceTest, SingleVirtualDeviceWithNoMemoryLimit) {
@@ -165,7 +183,7 @@ TEST_F(GPUDeviceTest, SingleVirtualDeviceWithNoMemoryLimit) {
165183
opts, kDeviceNamePrefix, &devices));
166184
EXPECT_EQ(1, devices.size());
167185
EXPECT_GE(devices[0]->attributes().memory_limit(), 0);
168-
for (auto d : devices) delete d;
186+
gtl::STLDeleteElements(&devices);
169187
}
170188

171189
TEST_F(GPUDeviceTest, SingleVirtualDeviceWithMemoryLimit) {
@@ -175,7 +193,7 @@ TEST_F(GPUDeviceTest, SingleVirtualDeviceWithMemoryLimit) {
175193
opts, kDeviceNamePrefix, &devices));
176194
EXPECT_EQ(1, devices.size());
177195
EXPECT_EQ(123 << 20, devices[0]->attributes().memory_limit());
178-
for (auto d : devices) delete d;
196+
gtl::STLDeleteElements(&devices);
179197
}
180198

181199
TEST_F(GPUDeviceTest, MultipleVirtualDevices) {
@@ -198,7 +216,67 @@ TEST_F(GPUDeviceTest, MultipleVirtualDevices) {
198216
devices[1]->attributes().locality().links().link(0).type());
199217
EXPECT_EQ(BaseGPUDeviceFactory::InterconnectMap::kSameDeviceStrength,
200218
devices[1]->attributes().locality().links().link(0).strength());
201-
for (auto d : devices) delete d;
219+
gtl::STLDeleteElements(&devices);
220+
}
221+
222+
// Enabling unified memory on pre-Pascal GPUs results in an initialization
223+
// error.
224+
TEST_F(GPUDeviceTest, UnifiedMemoryUnavailableOnPrePascalGpus) {
225+
int cc_major, cc_minor;
226+
TF_ASSERT_OK(GetComputeCapability(CudaGpuId(0), &cc_major, &cc_minor));
227+
// Exit early while running on Pascal or later GPUs.
228+
if (cc_major >= 6) {
229+
return;
230+
}
231+
232+
SessionOptions opts = MakeSessionOptions("0", /*memory_fraction=*/1.2);
233+
opts.config.mutable_gpu_options()
234+
->mutable_experimental()
235+
->set_use_unified_memory(true);
236+
std::vector<tensorflow::Device*> devices;
237+
Status status = DeviceFactory::GetFactory("GPU")->CreateDevices(
238+
opts, kDeviceNamePrefix, &devices);
239+
EXPECT_EQ(status.code(), error::INTERNAL);
240+
ExpectErrorMessageSubstr(status, "does not support oversubscription.");
241+
}
242+
243+
// Enabling unified memory on Pascal or later GPUs makes it possible to allocate
244+
// more memory than what is available on the device.
245+
TEST_F(GPUDeviceTest, UnifiedMemoryAllocation) {
246+
static constexpr double kGpuMemoryFraction = 1.2;
247+
static constexpr CudaGpuId kCudaGpuId(0);
248+
249+
int cc_major, cc_minor;
250+
TF_ASSERT_OK(GetComputeCapability(kCudaGpuId, &cc_major, &cc_minor));
251+
// Exit early if running on pre-Pascal GPUs.
252+
if (cc_major < 6) {
253+
LOG(INFO)
254+
<< "Unified memory allocation is not supported with pre-Pascal GPUs.";
255+
return;
256+
}
257+
258+
SessionOptions opts = MakeSessionOptions("0", kGpuMemoryFraction);
259+
std::vector<tensorflow::Device*> devices;
260+
TF_ASSERT_OK(DeviceFactory::GetFactory("GPU")->CreateDevices(
261+
opts, kDeviceNamePrefix, &devices));
262+
ASSERT_EQ(1, devices.size());
263+
264+
int64 memory_limit = devices[0]->attributes().memory_limit();
265+
ASSERT_EQ(memory_limit, static_cast<int64>(GetTotalGPUMemory(kCudaGpuId) *
266+
kGpuMemoryFraction));
267+
268+
AllocatorAttributes allocator_attributes = AllocatorAttributes();
269+
allocator_attributes.set_gpu_compatible(true);
270+
Allocator* allocator = devices[0]->GetAllocator(allocator_attributes);
271+
272+
// Try to allocate all the available memory after rounding down to the nearest
273+
// multiple of MB.
274+
void* ptr = allocator->AllocateRaw(Allocator::kAllocatorAlignment,
275+
(memory_limit >> 20) << 20);
276+
EXPECT_NE(ptr, nullptr);
277+
allocator->DeallocateRaw(ptr);
278+
279+
gtl::STLDeleteElements(&devices);
202280
}
203281

204282
} // namespace tensorflow

0 commit comments

Comments
 (0)