This repository was archived by the owner on Jul 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathtensorflow_v2.1.0_large_model_support.patch
3024 lines (2900 loc) · 106 KB
/
tensorflow_v2.1.0_large_model_support.patch
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
From 4a4c15b8c9853f9a677509547528a231c3f93a07 Mon Sep 17 00:00:00 2001
From: Samuel Matzek <[email protected]>
Date: Tue, 4 Feb 2020 11:05:20 -0600
Subject: [PATCH] TensorFlow Large Model Support for TensorFlow 2.1.0
This commit delivers TensorFlow Large Model Support
for TensorFlow at version 2.1.0.
See: https://github.com/IBM/tensorflow-large-model-support
Co-authored-by: Matthew Brandyberry <[email protected]>
Co-authored-by: Andres Lugo-Reyes <[email protected]>
---
tensorflow/c/eager/c_api.cc | 20 +
tensorflow/c/eager/c_api.h | 4 +
tensorflow/c/eager/tape.h | 1 +
tensorflow/c/tf_tensor.cc | 6 +-
tensorflow/compiler/jit/xla_launch_util.h | 6 +-
tensorflow/core/BUILD | 9 +-
tensorflow/core/common_runtime/bfc_allocator.cc | 415 ++++++++++++++++++++-
tensorflow/core/common_runtime/bfc_allocator.h | 81 +++-
tensorflow/core/common_runtime/executor.cc | 14 +-
.../core/common_runtime/gpu/gpu_bfc_allocator.cc | 104 +++++-
.../core/common_runtime/gpu/gpu_bfc_allocator.h | 25 ++
.../core/common_runtime/gpu/gpu_debug_allocator.cc | 8 +
.../core/common_runtime/gpu/gpu_debug_allocator.h | 2 +
tensorflow/core/common_runtime/gpu/gpu_device.cc | 3 +
.../core/common_runtime/gpu/gpu_event_mgr_test.cc | 3 +-
.../core/common_runtime/gpu/gpu_mem_allocator.h | 2 +
tensorflow/core/framework/allocator.cc | 25 +-
tensorflow/core/framework/allocator.h | 112 +++++-
tensorflow/core/framework/op_kernel.cc | 21 ++
tensorflow/core/framework/op_kernel.h | 10 +
tensorflow/core/framework/tensor.cc | 326 +++++++++++++++-
tensorflow/core/framework/tensor.h | 48 ++-
tensorflow/core/protobuf/config.proto | 6 +
tensorflow/lite/delegates/flex/buffer_map.cc | 5 +-
tensorflow/python/BUILD | 16 +
tensorflow/python/__init__.py | 1 +
tensorflow/python/eager/context.py | 48 ++-
tensorflow/python/eager/pywrap_tensor.cc | 21 ++
tensorflow/python/eager/pywrap_tfe_src.cc | 5 +
tensorflow/python/framework/bfc_allocator_stats.i | 401 ++++++++++++++++++++
tensorflow/python/framework/bfc_allocator_stats.py | 85 +++++
tensorflow/python/framework/config.py | 29 ++
tensorflow/python/keras/engine/network.py | 7 +-
tensorflow/python/tensorflow.i | 2 +
.../golden/v1/tensorflow.config.experimental.pbtxt | 16 +
.../api/golden/v1/tensorflow.experimental.pbtxt | 64 ++++
.../golden/v2/tensorflow.config.experimental.pbtxt | 16 +
.../api/golden/v2/tensorflow.experimental.pbtxt | 64 ++++
38 files changed, 1976 insertions(+), 55 deletions(-)
create mode 100644 tensorflow/python/framework/bfc_allocator_stats.i
create mode 100644 tensorflow/python/framework/bfc_allocator_stats.py
diff --git a/tensorflow/c/eager/c_api.cc b/tensorflow/c/eager/c_api.cc
index bffceab1bc..2d07769bf9 100644
--- a/tensorflow/c/eager/c_api.cc
+++ b/tensorflow/c/eager/c_api.cc
@@ -1,4 +1,5 @@
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
+ * Copyright 2019, 2020. IBM 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.
@@ -1253,6 +1254,25 @@ TFE_TensorHandle* TFE_TensorHandleCopyToDevice(TFE_TensorHandle* h,
return nullptr;
}
+void TFE_TensorHandle_SetGraphId(TFE_TensorHandle* h, int64_t id) {
+ if (h->handle == nullptr) return;
+ const tensorflow::Tensor* t = nullptr;
+ tensorflow::Status s = h->handle->Tensor(&t);
+ if (!s.ok()) return;
+ t->SetGraphId(id);
+}
+
+bool TFE_TensorHandle_GraphId(TFE_TensorHandle* h, int64_t* id) {
+ if (h->handle == nullptr) return false;
+ const tensorflow::Tensor* t = nullptr;
+ tensorflow::Status s = h->handle->Tensor(&t);
+ if (!s.ok()) return false;
+ tensorflow::int64 graph_id;
+ if (!t->GraphId(&graph_id)) return false;
+ *id = graph_id;
+ return true;
+}
+
void TFE_ContextAddFunctionDef(TFE_Context* ctx,
const char* serialized_function_def, size_t size,
TF_Status* status) {
diff --git a/tensorflow/c/eager/c_api.h b/tensorflow/c/eager/c_api.h
index d29e66dc1b..3484ef011c 100644
--- a/tensorflow/c/eager/c_api.h
+++ b/tensorflow/c/eager/c_api.h
@@ -1,4 +1,5 @@
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
+ * Copyright 2019, 2020. IBM 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.
@@ -193,6 +194,9 @@ TF_CAPI_EXPORT extern TFE_TensorHandle* TFE_TensorHandleCopyToDevice(
TFE_TensorHandle* h, TFE_Context* ctx, const char* device_name,
TF_Status* status);
+TF_CAPI_EXPORT extern void TFE_TensorHandle_SetGraphId(TFE_TensorHandle* h, int64_t id);
+TF_CAPI_EXPORT extern bool TFE_TensorHandle_GraphId(TFE_TensorHandle* h, int64_t* id);
+
// Debugging/Profiling information for TFE_TensorHandle
//
// TFE_TensorDebugInfo contains information useful for debugging and
diff --git a/tensorflow/c/eager/tape.h b/tensorflow/c/eager/tape.h
index 67edde38f9..c7a36f7cd6 100644
--- a/tensorflow/c/eager/tape.h
+++ b/tensorflow/c/eager/tape.h
@@ -624,6 +624,7 @@ Status InitialGradients(
// corresponding to index 0 is used, and the gradient values at indices 1-4 are
// ignored (and hence can be None). The backprop algorithm can then leverage
// this by not constructing zeros to pass for those indices.
+// TODO(mtbrandy): add FusedBatchNormV2 and V3 here?
std::unordered_map<string, std::unordered_set<int>>*
FunctionsAcceptingNoneForIndicesMap() {
static auto* const m =
diff --git a/tensorflow/c/tf_tensor.cc b/tensorflow/c/tf_tensor.cc
index 2ad778d605..e2da514518 100644
--- a/tensorflow/c/tf_tensor.cc
+++ b/tensorflow/c/tf_tensor.cc
@@ -28,6 +28,7 @@ limitations under the License.
using tensorflow::Status;
using tensorflow::Tensor;
using tensorflow::TensorBuffer;
+using tensorflow::SimpleTensorBufferBase;
using tensorflow::errors::FailedPrecondition;
using tensorflow::errors::InvalidArgument;
@@ -63,12 +64,12 @@ void deallocate_buffer(void* data, size_t len, void* arg) {
} // namespace tensorflow
namespace {
-class TF_ManagedBuffer : public TensorBuffer {
+class TF_ManagedBuffer : public SimpleTensorBufferBase {
public:
TF_ManagedBuffer(void* data, size_t len,
void (*deallocator)(void* data, size_t len, void* arg),
void* deallocator_arg)
- : TensorBuffer(data),
+ : SimpleTensorBufferBase(data),
len_(len),
deallocator_(deallocator),
deallocator_arg_(deallocator_arg) {}
@@ -82,7 +83,6 @@ class TF_ManagedBuffer : public TensorBuffer {
}
size_t size() const override { return len_; }
- TensorBuffer* root_buffer() override { return this; }
void FillAllocationDescription(
tensorflow::AllocationDescription* proto) const override {
tensorflow::int64 rb = size();
diff --git a/tensorflow/compiler/jit/xla_launch_util.h b/tensorflow/compiler/jit/xla_launch_util.h
index 81d63d299e..cfe6528d25 100644
--- a/tensorflow/compiler/jit/xla_launch_util.h
+++ b/tensorflow/compiler/jit/xla_launch_util.h
@@ -171,11 +171,11 @@ class XlaComputationLaunchContext {
// A simple TensorBuffer implementation that allows us to create Tensors that
// take ownership of pre-allocated memory.
-class XlaTensorBuffer : public TensorBuffer {
+class XlaTensorBuffer : public SimpleTensorBufferBase {
public:
XlaTensorBuffer(const void* ptr, size_t expected_size, size_t actual_size,
Allocator* allocator)
- : TensorBuffer(const_cast<void*>(ptr)),
+ : SimpleTensorBufferBase(const_cast<void*>(ptr)),
expected_size_(expected_size),
actual_size_(actual_size),
allocator_(allocator) {}
@@ -188,8 +188,6 @@ class XlaTensorBuffer : public TensorBuffer {
size_t size() const override { return expected_size_; }
- TensorBuffer* root_buffer() override { return this; }
-
void FillAllocationDescription(AllocationDescription* proto) const override {
proto->set_allocated_bytes(actual_size_);
}
diff --git a/tensorflow/core/BUILD b/tensorflow/core/BUILD
index 8369046aa8..9fe5a38e9c 100644
--- a/tensorflow/core/BUILD
+++ b/tensorflow/core/BUILD
@@ -3132,6 +3132,8 @@ cc_library(
visibility = ["//visibility:public"],
deps = [
":allocator",
+ ":framework",
+ ":framework_internal",
":lib",
":lib_internal",
":protos_all_cc",
@@ -3324,11 +3326,16 @@ tf_cuda_library(
srcs = [
"common_runtime/gpu/gpu_bfc_allocator.cc",
],
- hdrs = ["common_runtime/gpu/gpu_bfc_allocator.h"],
+ hdrs = [
+ "common_runtime/gpu/gpu_bfc_allocator.h",
+ "common_runtime/gpu/gpu_process_state.h",
+ "common_runtime/process_state.h",
+ ],
features = ["parse_headers"],
visibility = ["//visibility:public"],
deps = [
":bfc_allocator",
+ ":gpu_lib",
":gpu_mem_allocator",
":lib",
":lib_internal",
diff --git a/tensorflow/core/common_runtime/bfc_allocator.cc b/tensorflow/core/common_runtime/bfc_allocator.cc
index 3c0b2643c1..f8ffcfb70c 100644
--- a/tensorflow/core/common_runtime/bfc_allocator.cc
+++ b/tensorflow/core/common_runtime/bfc_allocator.cc
@@ -1,4 +1,5 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
+Copyright 2019, 2020. IBM 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.
@@ -18,6 +19,7 @@ limitations under the License.
#include <atomic>
#include "tensorflow/core/common_runtime/allocator_retry.h"
+#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/bits.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/str_util.h"
@@ -357,6 +359,373 @@ void BFCAllocator::DeallocateRegions(
}
}
+bool BFCAllocator::LMSReclaimHistory::predict() {
+ if (__builtin_popcountl(data_) > 1) {
+ int trailing_zeros = __builtin_ctzl(data_);
+ // 1. Detect simple pattern of one swap repeating at a regular frequency.
+ if (trailing_zeros == __builtin_ctzl(data_ >> (trailing_zeros + 1)))
+ return true;
+ // 2. Detect any repeating pattern over N encounters.
+ for (int N = trailing_zeros + 2; N <= 8; N++) {
+ // The pattern must start with a swap to predict a swap on this encounter.
+ uint64 start = 1UL << (N - 1);
+ uint64 mask = (start << 1) - 1;
+ if ((data_ & start) &&
+ (((data_ ^ (data_ >> N)) & mask) == 0))
+ return true;
+ }
+ }
+ return false;
+}
+
+void BFCAllocator::OccupyChunk(IntrusiveListHook<LMSTensorBuffer>* hook) {
+ if (!lms_defrag_enabled_)
+ return;
+ LMSTensorBuffer* tensor_buf = hook->elem();
+ void* ptr = tensor_buf->GetDevicePtr();
+ mutex_lock l(lock_);
+ BFCAllocator::ChunkHandle h = this->region_manager_.get_handle(ptr);
+ DCHECK(h != kInvalidChunkHandle);
+ Chunk* chunk = ChunkFromHandle(h);
+ chunk->lms_buf_hook = hook;
+}
+
+void BFCAllocator::VacateChunk(IntrusiveListHook<LMSTensorBuffer>* hook) {
+ if (!lms_defrag_enabled_)
+ return;
+ LMSTensorBuffer* tensor_buf = hook->elem();
+ void* ptr = tensor_buf->GetDevicePtr();
+ mutex_lock l(lock_);
+ BFCAllocator::ChunkHandle h = this->region_manager_.get_handle(ptr);
+ DCHECK(h != kInvalidChunkHandle);
+ Chunk* chunk = ChunkFromHandle(h);
+ chunk->lms_buf_hook = nullptr;
+}
+
+bool BFCAllocator::ReclaimListAdd(void* ptr, IntrusiveListHook<LMSTensorBuffer>* hook) {
+ LMSTensorBuffer* buf = hook->elem();
+ size_t size = buf->size();
+
+ mutex_lock l(lock_);
+ stats_.bytes_inactive += size;
+ reclaim_list_.append(hook);
+
+ VLOG(2) << "-> INACTIVE " << (void*)buf << " (" << size << ")";
+
+ int64 id;
+ bool pageout_predicted = buf->GraphId(&id) && reclaim_history_[id].predict();
+
+ if (reclaim_waiter_)
+ reclaim_cv_.notify_all();
+
+ return pageout_predicted;
+}
+
+bool BFCAllocator::ReclaimListRemove(void* ptr, IntrusiveListHook<LMSTensorBuffer>* hook) {
+ mutex_lock l(lock_);
+ return ReclaimListRemoveInternal(ptr, hook, false);
+}
+
+void BFCAllocator::ReclaimListNotify() {
+ mutex_lock l(lock_);
+ if (reclaim_waiter_)
+ reclaim_cv_.notify_all();
+}
+
+bool BFCAllocator::ReclaimListRemoveInternal(void* ptr, IntrusiveListHook<LMSTensorBuffer>* hook, bool reclaimed) {
+ bool removed = hook->remove();
+ CHECK(!reclaimed || removed); // reclaimed tensors must be on the list
+ if (removed) {
+ LMSTensorBuffer* buf = hook->elem();
+ size_t size = buf->size();
+ stats_.bytes_inactive -= size;
+ stats_.peak_bytes_active = std::max(stats_.peak_bytes_active, stats_.bytes_active());
+ if (!reclaimed) {
+ // Activate chunk
+ VLOG(2) << "ACTIVE <- " << (void*)buf << " (" << size << ")"
+ <<" [active: " << stats_.bytes_active() << ", inactive: " << stats_.bytes_inactive << "]";
+ } else {
+ // Free chunk
+ stats_.bytes_reclaimed += size;
+ DeallocateRawInternal(ptr);
+ }
+
+ int64 id;
+ if (buf->GraphId(&id)) {
+ LMSReclaimHistory& hist = reclaim_history_[id];
+ if (VLOG_IS_ON(2) &&
+ (!reclaimed || __builtin_popcountl(hist.data()) > 1) &&
+ hist.predict() != reclaimed) {
+ LOG(INFO) << "PREDICT: " << (reclaimed ? "MISS " : "WRONG ")
+ << (void*)buf << " (" << size << ")"
+ << " id=" << (void*)id
+ << " h=" << (void*)hist.data();
+ }
+ hist.record(reclaimed);
+ }
+
+ if (reclaim_waiter_)
+ reclaim_cv_.notify_all();
+ }
+
+ return removed;
+}
+
+BFCAllocator::ReclaimStatus BFCAllocator::TryReclaim(IntrusiveListHook<LMSTensorBuffer>* hook) {
+ LMSTensorBuffer* buf = hook->elem();
+ void* ptr = buf->TryPageout();
+ if (ptr == nullptr) {
+ // Pageout attempt was not successful. Wait on reclaim list notification and retry.
+ return ReclaimStatus::kRetry;
+ }
+ ReclaimListRemoveInternal(ptr, hook, true);
+ return ReclaimStatus::kSuccess;
+}
+
+BFCAllocator::ReclaimStatus BFCAllocator::ReclaimOne(size_t rounded_bytes) {
+ IntrusiveListHook<LMSTensorBuffer>* best = nullptr;
+ size_t best_size = ULONG_MAX;
+ auto hook = reclaim_list_.head();
+ auto end = reclaim_list_.terminator();
+ do {
+ LMSTensorBuffer* buf = hook->elem();
+ size_t size = RoundedBytes(buf->size());
+ if ( (size >= rounded_bytes) && (size < best_size) ) {
+ best = hook;
+ best_size = size;
+ if (size == rounded_bytes)
+ break;
+ }
+ hook = hook->next();
+ } while (hook != end);
+
+ if (best == nullptr)
+ return ReclaimStatus::kUnavailable;
+
+ return TryReclaim(best);
+}
+
+BFCAllocator::ReclaimStatus BFCAllocator::ReclaimFragments(size_t rounded_bytes) {
+ // TODO(mtbrandy): Attempt to reclaim smaller tensors that, when
+ // coalesced, will satisfy the request.
+ // Dumb and slow (but effective) placeholder implementation.
+ return ReclaimAll();
+}
+
+BFCAllocator::ReclaimStatus BFCAllocator::ReclaimAll() {
+ stats_.num_full_reclaims++;
+ ReclaimStatus status = ReclaimStatus::kUnavailable;
+ while (!reclaim_list_.empty() &&
+ (status = TryReclaim(reclaim_list_.head())) == ReclaimStatus::kSuccess);
+ return status;
+}
+
+void* BFCAllocator::ReclaimChunkPtr(BinNum bin_num, size_t rounded_bytes,
+ size_t num_bytes, uint64 freed_before,
+ mutex_lock& lock) {
+ while (!reclaim_list_.empty()) {
+ void* ptr;
+
+ // Reclaim a single suitable inactive allocation
+ auto status = ReclaimOne(rounded_bytes);
+ if (status == ReclaimStatus::kSuccess) {
+ stats_.num_single_reclaims++;
+ ptr = FindChunkPtr(bin_num, rounded_bytes, num_bytes, freed_before);
+ if (ptr != nullptr) {
+ return ptr;
+ }
+ VLOG(2) << "ReclaimOne: ineffective (" << rounded_bytes << ")";
+ continue;
+ }
+ // ReclaimFragments is currently a dummy impl which calls ReclaimAll.
+ // Commenting out the ReclaimFragments call until it gets a unique
+ // implementation to avoid a double call to ReclaimAll.
+
+ // if (status == ReclaimStatus::kUnavailable) {
+ // // Reclaim and coalesce fragments of suitable inactive allocations
+ // status = ReclaimFragments(rounded_bytes);
+ // if (status == ReclaimStatus::kSuccess) {
+ // ptr = FindChunkPtr(bin_num, rounded_bytes, num_bytes, freed_before);
+ // if (ptr != nullptr) {
+ // return ptr;
+ // }
+ // VLOG(2) << "ReclaimFragments: ineffective (" << rounded_bytes << ")";
+ // continue;
+ // }
+ // }
+
+ if (status == ReclaimStatus::kUnavailable) {
+ // Reclaim everything to give DeallocateFreeRegions the best chance of success.
+ status = ReclaimAll();
+ if (status == ReclaimStatus::kSuccess) {
+ ptr = FindChunkPtr(bin_num, rounded_bytes, num_bytes, freed_before);
+ if (ptr != nullptr) {
+ return ptr;
+ }
+ continue;
+ }
+ }
+
+ if (status == ReclaimStatus::kUnavailable) {
+ continue;
+ }
+
+ CHECK(status == ReclaimStatus::kRetry);
+ VLOG(2) << "ReclaimChunkPtr: wait (" << rounded_bytes << ")";
+ reclaim_waiter_++;
+ reclaim_cv_.wait(lock);
+ reclaim_waiter_--;
+ VLOG(2) << "ReclaimChunkPtr: notified (" << rounded_bytes << ")";
+
+ // Retry FindChunkPtr since the allocation map may have changed.
+ ptr = FindChunkPtr(bin_num, rounded_bytes, num_bytes, freed_before);
+ if (ptr != nullptr) {
+ return ptr;
+ }
+ } // end while reclaim list not empty
+ // At this point we have reclaimed all possible tensors and waited for all
+ // pageouts to complete and there is still not enough free space to
+ // satisfy the request.
+ if (lms_defrag_enabled_ && DefragmentFreeChunks(rounded_bytes, freed_before)) {
+ void* ptr = FindChunkPtr(bin_num, rounded_bytes, num_bytes, freed_before);
+ if (ptr != nullptr) {
+ return ptr;
+ }
+ }
+ return nullptr;
+}
+
+bool BFCAllocator::DefragmentFreeChunks(size_t rounded_bytes, uint64 freed_before) {
+ VLOG(2) << "DefragmentFreeChunks >";
+ if ((memory_limit_ - stats_.bytes_in_use) < rounded_bytes) {
+ VLOG(2) << "Insufficient free space to allocate "
+ <<rounded_bytes<< "bytes.";
+ return false;
+ }
+
+ // Look at a set of up to range_size contiguous chunks for fragmented
+ // free chunks that could be defragmented to satisfy the request
+ // for rounded_bytes. The range size is increased and chunks are searched
+ // again if no defragmentation region is found.
+ int range_size = 10;
+ // List of buffers to move as part of the defragmentation
+ std::vector<IntrusiveListHook<LMSTensorBuffer>*> defrag_buffers;
+ // Free bytes that will coalesced by moving the buffers in defrag_buffers
+ size_t free_size = 0;
+ size_t move_size = 0; //size of the chunks in the defrag_buffers list
+ size_t num_chunks = chunks_.size();
+ // Find the starting bin number. We start at a smaller bin than the bin
+ // that could satisfy the rounded bytes since smaller fragmented free chunks
+ // in that bin could coalesce during defragmentation and move to higher bins.
+ BinNum initial_bin = BinNumForSize(rounded_bytes/8);
+ while((free_size < rounded_bytes) && (range_size <= num_chunks)) {
+ VLOG(4) << "Looking at regions of "<< range_size <<" chunks.";
+ for (BinNum bin_num=initial_bin;
+ (bin_num < kNumBins) && (free_size < rounded_bytes); bin_num++) {
+ Bin* b = BinFromIndex(bin_num);
+ VLOG(4) << "Checking bin for: "
+ << strings::HumanReadableNumBytes(b->bin_size);
+ for (auto citer = b->free_chunks.begin();
+ (citer != b->free_chunks.end()) && (free_size < rounded_bytes);
+ ++citer) {
+ const BFCAllocator::ChunkHandle h = (*citer);
+ CHECK(h != kInvalidChunkHandle);
+ BFCAllocator::Chunk* chunk = ChunkFromHandle(h);
+ CHECK(chunk != nullptr);
+ DCHECK(!chunk->in_use());
+ free_size = chunk->size;
+ defrag_buffers.clear();
+ move_size = 0;
+ CHECK(chunk->ptr != nullptr);
+
+ VLOG(4) << "Searching forward from chunk at "<< chunk->ptr;
+ // look at up to range_size contiguous chunks from this starting
+ // free chunk.
+ for (int i=0; ((i < range_size) && (chunk->next != kInvalidChunkHandle)
+ && (free_size < rounded_bytes));
+ i++) {
+ CHECK(chunk != nullptr);
+ CHECK(chunk->next != kInvalidChunkHandle);
+ chunk = ChunkFromHandle(chunk->next);
+ CHECK(chunk != nullptr);
+ if (!chunk->in_use()) {
+ free_size += chunk->size;
+ }
+ else if (chunk->lms_buf_hook != nullptr) {
+ DCHECK((chunk->lms_buf_hook)->detached());
+ defrag_buffers.push_back(chunk->lms_buf_hook);
+ move_size += chunk->size;
+ }
+ else {
+ // A rare case of in use chunk that is not occupied by a TensorBuffer.
+ // We can't safely move this chunk so we break and restart the search
+ // from the next free chunk in this bin.
+ break;
+ }
+ }//end search forward from chunk
+ VLOG(4) << "Done searching forward from chunk at "<< chunk->ptr;
+ }//end search free chunks in bin
+ VLOG(4) << "Done free in bin";
+ }//end search all bins
+ VLOG(4) << "Done all bins";
+ range_size = (range_size < num_chunks) ? std::min<std::size_t>(range_size * 2, num_chunks) : range_size + 1;
+ }//end while increasing range size
+
+ if (free_size >= rounded_bytes) {
+ stats_.num_defragmentations++;
+
+ if (VLOG_IS_ON(2)) {
+ string buf = strings::StrCat("\nA contiguous block of ", free_size,
+ " bytes ", "could be created by moving ", defrag_buffers.size(),
+ " tensors of cumulative size ", move_size,
+ " bytes at locations: ");
+ for (auto citer = defrag_buffers.begin(); citer != defrag_buffers.end();
+ ++citer) {
+ LMSTensorBuffer* tbuf = (*citer)->elem();
+ void* ptr = tbuf->GetDevicePtr();
+ strings::StrAppend(&buf, strings::Hex(reinterpret_cast<uint64>(ptr)),
+ ", ");
+
+ }
+ VLOG(2) << buf << "\n";
+ }
+
+ // First page out all buffers in the contiguous memory block and
+ // deallocate the memory which will allow the contiguous block to
+ // coalesce.
+ std::vector<IntrusiveListHook<LMSTensorBuffer>*> pagedout_buffers;
+ for (auto citer = defrag_buffers.begin(); citer != defrag_buffers.end();
+ ++citer) {
+ LMSTensorBuffer* tbuf = (*citer)->elem();
+ void* device_ptr = tbuf->TryPageout();
+ if (device_ptr == nullptr) {
+ LOG(ERROR) << "Pageout of " << device_ptr << " failed.";
+ break;
+ }
+ stats_.bytes_defragged += tbuf->size();
+ pagedout_buffers.push_back((*citer));
+ DeallocateRawInternal(device_ptr);
+ }
+
+ // Next, page in the buffers that were paged out above.
+ bool return_val = (defrag_buffers.size() == pagedout_buffers.size());
+ for (auto citer = pagedout_buffers.begin(); citer != pagedout_buffers.end();
+ ++citer) {
+ LMSTensorBuffer* tbuf = (*citer)->elem();
+ size_t pagein_size = tbuf->size();
+ size_t pagein_rounded = RoundedBytes(pagein_size);
+ BinNum bin_num = BinNumForSize(pagein_rounded);
+ void* ptr = FindChunkPtr(bin_num, pagein_rounded, pagein_size, freed_before);
+ DCHECK(ptr != nullptr);
+ tbuf->Pagein(ptr);
+ }
+ VLOG(2) << "DefragmentFreeChunks <";
+ return return_val;
+ }
+ VLOG(2) << "DefragmentFreeChunks <";
+ return false;
+}
+
void* BFCAllocator::AllocateRawInternal(size_t unused_alignment,
size_t num_bytes,
bool dump_log_on_failure,
@@ -404,6 +773,14 @@ void* BFCAllocator::AllocateRawInternal(size_t unused_alignment,
}
}
+ // Try to swap out eligible tensor(s)
+ if (lms_enabled_) {
+ ptr = ReclaimChunkPtr(bin_num, rounded_bytes, num_bytes, freed_before, l);
+ if (ptr != nullptr) {
+ return ptr;
+ }
+ }
+
// Reaching this point means that no chunks can satisfy the request. Also,
// the unallocated bytes cannot satisfy the request. Before giving up, let's
// try deallocating free regions so that suballocator can combine them with
@@ -427,6 +804,20 @@ void* BFCAllocator::AllocateRawInternal(size_t unused_alignment,
<< "). Current allocation summary follows.";
DumpMemoryLog(rounded_bytes);
LOG(WARNING) << RenderOccupancy();
+
+ if (!lms_enabled_) {
+ LOG(WARNING) << "Enabling Large Model Support may avoid this failure.";
+ }
+ else if (lms_enabled_ && !lms_defrag_enabled_ &&
+ ((memory_limit_ - stats_.bytes_in_use) >= rounded_bytes)) {
+ // There should be enough memory to satisfy the request, but
+ // we were not able to find a contiguous section due to memory
+ // fragmentation.
+ LOG(WARNING) << "Enough free memory to satisfy the allocation request "
+ << "exists but it is fragmented. Enabling Large Model "
+ << "Support defragmentation may avoid this failure.";
+ }
+
}
return nullptr;
}
@@ -474,6 +865,7 @@ void* BFCAllocator::FindChunkPtr(BinNum bin_num, size_t rounded_bytes,
stats_.bytes_in_use += chunk->size;
stats_.peak_bytes_in_use =
std::max(stats_.peak_bytes_in_use, stats_.bytes_in_use);
+ stats_.peak_bytes_active = std::max(stats_.peak_bytes_active, stats_.bytes_active());
stats_.largest_alloc_size =
std::max<std::size_t>(stats_.largest_alloc_size, chunk->size);
@@ -548,16 +940,17 @@ void BFCAllocator::SplitChunk(BFCAllocator::ChunkHandle h, size_t num_bytes) {
void BFCAllocator::DeallocateRaw(void* ptr) {
VLOG(1) << "DeallocateRaw " << Name() << " "
<< (ptr ? RequestedSize(ptr) : 0);
- DeallocateRawInternal(ptr);
- retry_helper_.NotifyDealloc();
-}
-
-void BFCAllocator::DeallocateRawInternal(void* ptr) {
if (ptr == nullptr) {
VLOG(2) << "tried to deallocate nullptr";
return;
+ } else {
+ mutex_lock l(lock_);
+ DeallocateRawInternal(ptr);
}
- mutex_lock l(lock_);
+ retry_helper_.NotifyDealloc();
+}
+
+void BFCAllocator::DeallocateRawInternal(void* ptr) {
// Find the chunk from the ptr.
BFCAllocator::ChunkHandle h = region_manager_.get_handle(ptr);
@@ -653,6 +1046,7 @@ void BFCAllocator::MarkFree(BFCAllocator::ChunkHandle h) {
// Mark the chunk as no longer in use.
c->allocation_id = -1;
+ c->lms_buf_hook = nullptr;
// Optionally record the free time.
if (timing_counter_) {
@@ -935,7 +1329,7 @@ void BFCAllocator::DumpMemoryLog(size_t num_bytes) {
in_use_by_size[c->size]++;
}
string buf = strings::StrCat(
- (c->in_use() ? "InUse" : "Free "), " at ",
+ c->usage_string(), " at ",
strings::Hex(reinterpret_cast<uint64>(c->ptr)), " of size ", c->size);
#ifdef TENSORFLOW_MEM_DEBUG
if (ShouldRecordOpName()) {
@@ -1083,6 +1477,13 @@ void BFCAllocator::ClearStats() {
stats_.num_allocs = 0;
stats_.peak_bytes_in_use = stats_.bytes_in_use;
stats_.largest_alloc_size = 0;
+ stats_.peak_bytes_active = stats_.bytes_active();
+ stats_.bytes_reclaimed = 0;
+ stats_.num_single_reclaims = 0;
+ stats_.num_full_reclaims = 0;
+ stats_.num_defragmentations = 0;
+ stats_.bytes_defragged = 0;
+
}
std::array<BFCAllocator::BinDebugInfo, BFCAllocator::kNumBins>
diff --git a/tensorflow/core/common_runtime/bfc_allocator.h b/tensorflow/core/common_runtime/bfc_allocator.h
index 7c2749d6a6..b49997790c 100644
--- a/tensorflow/core/common_runtime/bfc_allocator.h
+++ b/tensorflow/core/common_runtime/bfc_allocator.h
@@ -1,4 +1,5 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
+Copyright 2019, 2020. IBM 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.
@@ -46,7 +47,7 @@ class MemoryDump;
// coalescing. One assumption we make is that the process using this
// allocator owns pretty much all of the memory, and that nearly
// all requests to allocate memory go through this interface.
-class BFCAllocator : public Allocator {
+class BFCAllocator : public LMSAllocator {
public:
// Takes ownership of sub_allocator.
BFCAllocator(SubAllocator* sub_allocator, size_t total_memory,
@@ -85,6 +86,19 @@ class BFCAllocator : public Allocator {
MemoryDump RecordMemoryMap();
+ void SetLMSConfig(bool enabled, bool defrag_enabled) {
+ lms_enabled_ = enabled;
+ lms_defrag_enabled_ = defrag_enabled;
+ }
+ LMSAllocator* AsLMSAllocator() final {
+ return (lms_enabled_) ? this : nullptr;
+ }
+ bool ReclaimListAdd(void* ptr, IntrusiveListHook<LMSTensorBuffer>* hook) override;
+ bool ReclaimListRemove(void* ptr, IntrusiveListHook<LMSTensorBuffer>* hook) override;
+ void ReclaimListNotify() override;
+ void OccupyChunk(IntrusiveListHook<LMSTensorBuffer>* hook) override;
+ void VacateChunk(IntrusiveListHook<LMSTensorBuffer>* hook) override;
+
private:
struct Bin;
@@ -168,10 +182,38 @@ class BFCAllocator : public Allocator {
// What bin are we in?
BinNum bin_num = kInvalidBinNum;
+ // Large Model Support
+ // The IntrusiveListHook for the LMSTensorBuffer occupying this chunk.
+ IntrusiveListHook<LMSTensorBuffer>* lms_buf_hook = nullptr;
+
// Optional count when this chunk was most recently made free.
uint64 freed_at_count = 0;
bool in_use() const { return allocation_id != -1; }
+ string usage_string() const {
+ // There are 4 usage strings:
+ // Free: The chunk is free
+ // InUse: The chunk is in use without referencing an occupying tensor.
+ // InUseA: The chunk is in use and occupied by an active tensor.
+ // InUseI: The chunk is in use and occupied by an inactive tensor.
+ // String are space padded to have equal length
+ if (allocation_id != -1) {
+ if (lms_buf_hook != nullptr) {
+ if (lms_buf_hook->detached()) {
+ return "InUseA";
+ }
+ else {
+ return "InUseI";
+ }
+ }
+ else {
+ return "InUse ";
+ }
+ }
+ else {
+ return "Free ";
+ }
+ }
#ifdef TENSORFLOW_MEM_DEBUG
// optional debugging info
@@ -540,6 +582,43 @@ class BFCAllocator : public Allocator {
int64 size_history_[MEM_DEBUG_SIZE_HISTORY_SIZE];
#endif
+ // Large Model Support
+ class LMSReclaimHistory {
+ public:
+ void record(bool reclaimed) {
+ data_ <<= 1;
+ if (reclaimed)
+ data_ |= 1UL;
+ }
+ bool predict();
+ int64 data() const { return data_; }
+
+ private:
+ uint64 data_ = 0;
+ };
+
+ bool lms_enabled_ = false;
+ bool lms_defrag_enabled_ = false;
+ bool DefragmentFreeChunks(size_t rounded_bytes, uint64 freed_before);
+ IntrusiveList<LMSTensorBuffer> reclaim_list_ GUARDED_BY(lock_);
+ std::unordered_map<int64, LMSReclaimHistory> reclaim_history_ GUARDED_BY(lock_);
+ condition_variable reclaim_cv_;
+ int reclaim_waiter_ = 0;
+ bool ReclaimListRemoveInternal(void* ptr, IntrusiveListHook<LMSTensorBuffer>* hook, bool reclaimed)
+ EXCLUSIVE_LOCKS_REQUIRED(lock_);
+
+ enum class ReclaimStatus {
+ kSuccess,
+ kUnavailable,
+ kRetry,
+ };
+ ReclaimStatus TryReclaim(IntrusiveListHook<LMSTensorBuffer>* hook) EXCLUSIVE_LOCKS_REQUIRED(lock_);
+ ReclaimStatus ReclaimOne(size_t rounded_bytes) EXCLUSIVE_LOCKS_REQUIRED(lock_);
+ ReclaimStatus ReclaimFragments(size_t rounded_bytes) EXCLUSIVE_LOCKS_REQUIRED(lock_);
+ ReclaimStatus ReclaimAll() EXCLUSIVE_LOCKS_REQUIRED(lock_);
+ void* ReclaimChunkPtr(BinNum bin_num, size_t rounded_bytes, size_t num_bytes, uint64 freed_before,
+ mutex_lock& lock) EXCLUSIVE_LOCKS_REQUIRED(lock_);
+
friend class GPUBFCAllocatorPrivateMethodsTest;
TF_DISALLOW_COPY_AND_ASSIGN(BFCAllocator);
};
diff --git a/tensorflow/core/common_runtime/executor.cc b/tensorflow/core/common_runtime/executor.cc
index 9cfa31c261..1ae17c02cf 100644
--- a/tensorflow/core/common_runtime/executor.cc
+++ b/tensorflow/core/common_runtime/executor.cc
@@ -1,4 +1,5 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
+Copyright 2019, 2020. IBM 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.
@@ -218,6 +219,11 @@ struct NodeItem {
// 0... for forward from that input.
const int* forward_from() const { return forward_from_base(); }
+ // Return a unique Id in the graph for the given output.
+ int64 output_graphId(int i) const {
+ return reinterpret_cast<std::intptr_t>(&output_attr_base()[i]);
+ }
+
string DebugString() const {
string ret = strings::StrCat("{name:'", kernel->name(), "' id:", node_id);
if (is_source) {
@@ -2083,8 +2089,12 @@ Status ExecutorState::ProcessOutputs(const NodeItem& item, OpKernelContext* ctx,
// we are in the tensor buffer.
DataType dtype = val.dtype_safe();
if (dtype == item.output_type(i)) {
- if (stats && val.tensor->IsInitialized()) {
- nodestats::SetOutput(stats, i, val.tensor);
+ Tensor* t = val.tensor;
+ if (t->IsInitialized()) {
+ if (stats) {
+ nodestats::SetOutput(stats, i, t);
+ }
+ t->SetGraphId(item.output_graphId(i));
}
if (val.is_ref()) {
out->has_value = true;
diff --git a/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc b/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc
index aeb5d33f3c..bac7e13767 100644
--- a/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc
+++ b/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc
@@ -1,4 +1,5 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
+Copyright 2019, 2020. IBM 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.
@@ -14,7 +15,9 @@ limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h"
+#include "tensorflow/core/common_runtime/gpu/gpu_process_state.h"
+#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/strings/strcat.h"
namespace tensorflow {
@@ -83,6 +86,105 @@ GPUBFCAllocator::GPUBFCAllocator(GPUMemAllocator* sub_allocator,
const string& name)
: BFCAllocator(sub_allocator, total_memory,
GPUBFCAllocator::GetAllowGrowthValue(gpu_options), name,
- GPUBFCAllocator::GetGarbageCollectionValue()) {}
+ GPUBFCAllocator::GetGarbageCollectionValue()),
+ stream_exec_(sub_allocator->stream_executor()) {
+ if (gpu_options.experimental().lms_enabled()) {
+ SetLMSConfig(true, gpu_options.experimental().lms_defrag_enabled());
+ H2D_stream_ = new se::Stream(stream_exec_);
+ H2D_stream_->Init();
+ D2H_stream_ = new se::Stream(stream_exec_);
+ D2H_stream_->Init();
+ event_mgr_ = EventMgrFactory::Singleton()->GetEventMgr(stream_exec_, gpu_options);
+ }
+}
+
+void GPUBFCAllocator::SetStreams(se::Stream* compute) {
+ compute_stream_ = compute;
+}
+
+void* GPUBFCAllocator::Pagein(const LMSTensorBuffer *buf) {
+ size_t nbytes = buf->size();
+ void *host_ptr = buf->GetHostPtr();
+ void *device_ptr = AllocateRaw(Allocator::kAllocatorAlignment, nbytes);
+
+ VLOG(2) << "PAGEIN <- " << (void*)buf << " (" << nbytes << ")";
+ se::DeviceMemoryBase dst(device_ptr, nbytes);
+ auto result = stream_exec_->SynchronousMemcpyH2D(host_ptr, nbytes, &dst);
+ CHECK(result.ok());
+ return device_ptr;
+}
+
+void* GPUBFCAllocator::PageinAsync(const LMSTensorBuffer *buf,
+ const std::function<void()>& done) {
+ size_t nbytes = buf->size();
+ void *host_ptr = buf->GetHostPtr();
+ void *device_ptr = buf->GetDevicePtr();
+
+ if (device_ptr == nullptr) {
+ device_ptr = AllocateRaw(Allocator::kAllocatorAlignment, nbytes);
+ }
+
+ VLOG(2) << "PAGEIN <- " << (void*)buf << " (" << nbytes << ") ASYNC";
+ se::DeviceMemoryBase dst(device_ptr, nbytes);
+
+ // Wait for the compute stream to make sure the device buffer is truly available.
+ H2D_stream_->ThenWaitFor(compute_stream_);
+
+ H2D_stream_->ThenMemcpy(&dst, host_ptr, nbytes);
+ event_mgr_->ThenExecute(H2D_stream_,
+ [this, done]() {
+ CHECK(this->H2D_stream_->ok());
+ done();
+ });
+ return device_ptr;
+}
+
+void* GPUBFCAllocator::Pageout(const LMSTensorBuffer *buf) {
+ size_t nbytes = buf->size();
+ void *device_ptr = buf->GetDevicePtr();
+ void *host_ptr = buf->GetHostPtr();
+ if (host_ptr == nullptr) {
+ host_ptr = host_allocator()->AllocateRaw(Allocator::kAllocatorAlignment, nbytes);
+ }
+
+ VLOG(2) << "-> PAGEOUT " << (void*)buf << " (" << nbytes << ")";
+ const se::DeviceMemoryBase src(device_ptr, nbytes);
+ auto result = stream_exec_->SynchronousMemcpyD2H(src, nbytes, host_ptr);
+ CHECK(result.ok());
+ return host_ptr;
+}
+
+void* GPUBFCAllocator::PageoutAsync(const LMSTensorBuffer *buf,
+ const std::function<void()>& done) {
+ size_t nbytes = buf->size();
+ void *device_ptr = buf->GetDevicePtr();
+ void *host_ptr = buf->GetHostPtr();
+ if (host_ptr == nullptr) {
+ host_ptr = host_allocator()->AllocateRaw(Allocator::kAllocatorAlignment, nbytes);
+ }
+
+ VLOG(2) << "-> PAGEOUT " << (void*)buf << " (" << nbytes << ") ASYNC";
+ const se::DeviceMemoryBase src(device_ptr, nbytes);
+
+ // Wait for the compute stream to make sure the data is available.
+ D2H_stream_->ThenWaitFor(compute_stream_);
+
+ D2H_stream_->ThenMemcpy(host_ptr, src, nbytes);
+ event_mgr_->ThenExecute(D2H_stream_,
+ [this, done]() {
+ CHECK(this->D2H_stream_->ok());
+ done();
+ });
+ return host_ptr;
+}
+
+void GPUBFCAllocator::HostMemoryDeallocate(void *host_ptr) {
+ host_allocator()->DeallocateRaw(host_ptr);
+}
+
+void GPUBFCAllocator::EnsureHostAllocator() {
+ std::call_once(host_allocator_init_,
+ [&] { host_allocator_ = GPUProcessState::singleton()->GetGpuHostAllocator(0); });
+}
} // namespace tensorflow
diff --git a/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h b/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h
index 02b1a7418d..aebb96b4c0 100644
--- a/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h
+++ b/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h
@@ -1,4 +1,5 @@
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
+Copyright 2019, 2020. IBM All Rights Reserved.