Repository navigation
Expand file tree
/
Copy pathbfc_allocator.cc
More file actions
1178 lines (1040 loc) · 40.8 KB
/
Copy pathbfc_allocator.cc
File metadata and controls
1178 lines (1040 loc) · 40.8 KB
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
/* Copyright 2015 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/core/common_runtime/bfc_allocator.h"
#include <atomic>
#include "absl/strings/string_view.h"
#include "tensorflow/core/common_runtime/allocator_retry.h"
#include "tensorflow/core/lib/core/bits.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/file_system.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#ifdef TENSORFLOW_MEM_DEBUG
#include "tensorflow/core/platform/stacktrace.h"
#endif
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/lib/traceme.h"
#include "tensorflow/core/protobuf/bfc_memory_map.pb.h"
namespace tensorflow {
BFCAllocator::BFCAllocator(SubAllocator* sub_allocator, size_t total_memory,
bool allow_growth, const string& name,
bool garbage_collection)
: garbage_collection_(garbage_collection),
sub_allocator_(sub_allocator),
name_(name),
free_chunks_list_(kInvalidChunkHandle),
next_allocation_id_(1) {
if (allow_growth) {
// 1MiB smallest initial allocation, unless total memory available
// is less.
curr_region_allocation_bytes_ =
RoundedBytes(std::min(total_memory, size_t{1048576}));
} else {
curr_region_allocation_bytes_ = RoundedBytes(total_memory);
}
// Allocate the requested amount of memory.
memory_limit_ = total_memory;
stats_.bytes_limit = static_cast<int64>(total_memory);
// Create a bunch of bins of various good sizes.
// We create bins to fit all possible ranges that cover the
// memory_limit_ starting from allocations up to 256 bytes to
// allocations up to (and including) the memory limit.
for (BinNum b = 0; b < kNumBins; b++) {
size_t bin_size = BinNumToSize(b);
VLOG(1) << "Creating bin of max chunk size "
<< strings::HumanReadableNumBytes(bin_size);
new (BinFromIndex(b)) Bin(this, bin_size);
CHECK_EQ(BinForSize(bin_size), BinFromIndex(b));
CHECK_EQ(BinForSize(bin_size + 255), BinFromIndex(b));
CHECK_EQ(BinForSize(bin_size * 2 - 1), BinFromIndex(b));
if (b + 1 < kNumBins) {
CHECK_NE(BinForSize(bin_size * 2), BinFromIndex(b));
}
}
}
BFCAllocator::~BFCAllocator() {
// Return memory back.
VLOG(2) << "Number of regions allocated: "
<< region_manager_.regions().size();
for (const auto& region : region_manager_.regions()) {
sub_allocator_->Free(region.ptr(), region.memory_size());
}
for (BinNum b = 0; b < kNumBins; b++) {
BinFromIndex(b)->~Bin();
}
}
BFCAllocator::Chunk* BFCAllocator::ChunkFromHandle(ChunkHandle h) {
DCHECK_GE(h, 0);
DCHECK_LT(h, static_cast<int>(chunks_.size()));
return &(chunks_[h]);
}
const BFCAllocator::Chunk* BFCAllocator::ChunkFromHandle(ChunkHandle h) const {
DCHECK_GE(h, 0);
DCHECK_LT(h, static_cast<int>(chunks_.size()));
return &(chunks_[h]);
}
bool BFCAllocator::Extend(size_t alignment, size_t rounded_bytes) {
size_t available_bytes = memory_limit_ - total_region_allocated_bytes_;
// Rounds available_bytes down to the nearest multiple of kMinAllocationSize.
available_bytes = (available_bytes / kMinAllocationSize) * kMinAllocationSize;
// Do we have enough space to handle the client's request?
// If not, fail immediately.
if (rounded_bytes > available_bytes) {
return false;
}
// If curr_region_allocation_bytes_ is not enough to satisfy the
// allocation, keep multiplying by a power of two until that is
// sufficient.
bool increased_allocation = false;
while (rounded_bytes > curr_region_allocation_bytes_) {
curr_region_allocation_bytes_ *= 2;
increased_allocation = true;
}
// Try allocating.
size_t bytes = std::min(curr_region_allocation_bytes_, available_bytes);
void* mem_addr = sub_allocator_->Alloc(alignment, bytes);
if (mem_addr == nullptr && !started_backpedal_) {
// Only backpedal once.
started_backpedal_ = true;
static constexpr float kBackpedalFactor = 0.9;
// Try allocating less memory.
while (mem_addr == nullptr) {
bytes = RoundedBytes(bytes * kBackpedalFactor);
if (bytes < rounded_bytes) break;
mem_addr = sub_allocator_->Alloc(alignment, bytes);
}
}
if (mem_addr == nullptr) {
return false;
}
if (!increased_allocation) {
// Increase the region size of the next required allocation.
curr_region_allocation_bytes_ *= 2;
}
VLOG(1) << "Extending allocation by " << strings::HumanReadableNumBytes(bytes)
<< " bytes.";
total_region_allocated_bytes_ += bytes;
VLOG(1) << "Total allocated bytes: "
<< strings::HumanReadableNumBytes(total_region_allocated_bytes_);
VLOG(1) << "Allocated memory at " << mem_addr << " to "
<< static_cast<void*>(static_cast<char*>(mem_addr) + bytes);
region_manager_.AddAllocationRegion(mem_addr, bytes);
// Create one large chunk for the whole memory space that will
// be chunked later.
ChunkHandle h = AllocateChunk();
BFCAllocator::Chunk* c = ChunkFromHandle(h);
c->ptr = mem_addr;
c->size = bytes;
c->allocation_id = -1;
c->prev = kInvalidChunkHandle;
c->next = kInvalidChunkHandle;
c->freed_at_count = 0;
region_manager_.set_handle(c->ptr, h);
// Insert the chunk into the right bin.
InsertFreeChunkIntoBin(h);
return true;
}
BFCAllocator::ChunkHandle BFCAllocator::AllocateChunk() {
if (free_chunks_list_ != kInvalidChunkHandle) {
ChunkHandle h = free_chunks_list_;
Chunk* c = ChunkFromHandle(h);
free_chunks_list_ = c->next;
return h;
} else {
ChunkHandle h = chunks_.size();
chunks_.resize(h + 1);
return h;
}
}
void BFCAllocator::DeallocateChunk(ChunkHandle h) {
Chunk* c = ChunkFromHandle(h);
c->allocation_id = -1;
c->bin_num = kInvalidBinNum;
c->next = free_chunks_list_;
free_chunks_list_ = h;
}
void* BFCAllocator::AllocateRawInternalWithRetry(
size_t unused_alignment, size_t num_bytes,
const AllocationAttributes& allocation_attr) {
// Fast path: Try once to allocate without getting the retry_helper_ involved
uint64 freed_by_count = 0;
if (allocation_attr.freed_by_func != nullptr) {
freed_by_count = (*allocation_attr.freed_by_func)();
}
void* r =
AllocateRawInternal(unused_alignment, num_bytes, false, freed_by_count);
if (r != nullptr) {
return r;
} else {
static const int64 kMaxMillisToWait = 10000; // 10 seconds
r = retry_helper_.AllocateRaw(
[this, &allocation_attr](size_t a, size_t nb, bool v) {
uint64 freed_by_count = 0;
if (allocation_attr.freed_by_func != nullptr) {
freed_by_count = (*allocation_attr.freed_by_func)();
}
return AllocateRawInternal(a, nb, v, freed_by_count);
},
kMaxMillisToWait, unused_alignment, num_bytes);
return r;
}
}
void* BFCAllocator::AllocateRaw(size_t unused_alignment, size_t num_bytes,
const AllocationAttributes& allocation_attr) {
VLOG(1) << "AllocateRaw " << Name() << " " << num_bytes;
if (allocation_attr.no_retry_on_failure) {
// Return immediately upon the first failure if this is for allocating an
// optional scratch space.
bool dump_log_on_failure = VLOG_IS_ON(2);
uint64 freed_by_count = 0;
if (allocation_attr.freed_by_func != nullptr) {
freed_by_count = (*allocation_attr.freed_by_func)();
}
void* result = AllocateRawInternal(unused_alignment, num_bytes,
dump_log_on_failure, freed_by_count);
if (result == nullptr) {
static std::atomic<int32> log_counter{0};
int32 counter_value = log_counter.load(std::memory_order_relaxed);
if (counter_value < 10) {
log_counter.store(counter_value + 1, std::memory_order_relaxed);
LOG(WARNING)
<< "Allocator (" << Name() << ") ran out of memory trying "
<< "to allocate " << strings::HumanReadableNumBytes(num_bytes)
<< " with freed_by_count=" << freed_by_count
<< ". The caller indicates that this is not a failure, but"
<< " may mean that there could be performance gains if more"
<< " memory were available.";
}
}
return result;
} else {
return AllocateRawInternalWithRetry(unused_alignment, num_bytes,
allocation_attr);
}
}
// static
size_t BFCAllocator::RoundedBytes(size_t bytes) {
size_t rounded_bytes =
(kMinAllocationSize *
((bytes + kMinAllocationSize - 1) / kMinAllocationSize));
DCHECK_EQ(size_t{0}, rounded_bytes % kMinAllocationSize);
return rounded_bytes;
}
bool BFCAllocator::DeallocateFreeRegions(size_t rounded_bytes)
TF_EXCLUSIVE_LOCKS_REQUIRED(lock_) {
// Do nothing if garbage collection is off.
if (!garbage_collection_) {
return false;
}
// Searching for free regions.
absl::flat_hash_set<void*> free_region_ptrs;
size_t total_free_bytes = 0;
for (const AllocationRegion& region : region_manager_.regions()) {
ChunkHandle h = region_manager_.get_handle(region.ptr());
bool any_use = false;
while (h != kInvalidChunkHandle) {
const Chunk* c = ChunkFromHandle(h);
if (c->in_use()) {
any_use = true;
break;
}
h = c->next;
}
if (!any_use) {
VLOG(2) << "Found free region with ptr = " << region.ptr();
free_region_ptrs.insert(region.ptr());
total_free_bytes += region.memory_size();
}
}
if (total_free_bytes == 0) {
return false;
}
// Rough estimation to check whether deallocation can help.
size_t available_bytes =
memory_limit_ - total_region_allocated_bytes_ + total_free_bytes;
if (rounded_bytes > available_bytes) {
return false;
}
LOG(WARNING) << "Garbage collection: deallocate free memory regions"
<< " (i.e., allocations) so that we can re-allocate a larger"
<< " region to avoid OOM due to memory fragmentation. If you"
<< " see this message frequently, you are running near the"
<< " threshold of the available device memory and re-allocation"
<< " may incur great performance overhead. You may try smaller"
<< " batch sizes to observe the performance impact."
<< " Set TF_ENABLE_GPU_GARBAGE_COLLECTION=false if you'd like to"
<< " disable this feature.";
// Deallocate free regions.
DeallocateRegions(free_region_ptrs);
return true;
}
void BFCAllocator::DeallocateRegions(
const absl::flat_hash_set<void*>& region_ptrs)
TF_EXCLUSIVE_LOCKS_REQUIRED(lock_) {
// Explicitly remove the const qualifier as some compilers disallow passing
// const_iterator to std::vector::erase(), which is used in
// RemoveAllocationRegion().
auto regions =
const_cast<std::vector<AllocationRegion>*>(®ion_manager_.regions());
auto it = regions->begin();
while (it != regions->end()) {
if (!region_ptrs.contains(it->ptr())) {
++it;
continue;
}
VLOG(2) << "Deallocate region with ptr = " << it->ptr();
// Remove all chunk registrations from Bins.
ChunkHandle h = region_manager_.get_handle(it->ptr());
while (h != kInvalidChunkHandle) {
const Chunk* c = ChunkFromHandle(h);
if (c->bin_num != kInvalidBinNum) {
RemoveFreeChunkFromBin(h);
}
auto h_to_delete = h;
h = c->next;
DeleteChunk(h_to_delete);
}
// Deallocate the memory.
sub_allocator_->Free(it->ptr(), it->memory_size());
total_region_allocated_bytes_ -= it->memory_size();
it = region_manager_.RemoveAllocationRegion(it);
}
}
void* BFCAllocator::AllocateRawInternal(size_t unused_alignment,
size_t num_bytes,
bool dump_log_on_failure,
uint64 freed_before) {
if (num_bytes == 0) {
VLOG(2) << "tried to allocate 0 bytes";
return nullptr;
}
// First, always allocate memory of at least kMinAllocationSize
// bytes, and always allocate multiples of kMinAllocationSize bytes
// so all memory addresses are nicely byte aligned.
size_t rounded_bytes = RoundedBytes(num_bytes);
// The BFC allocator tries to find the best fit first.
BinNum bin_num = BinNumForSize(rounded_bytes);
mutex_lock l(lock_);
if (!timestamped_chunks_.empty()) {
// Merge timestamped chunks whose counts have become safe for general use.
MergeTimestampedChunks(0);
}
void* ptr = FindChunkPtr(bin_num, rounded_bytes, num_bytes, freed_before);
if (ptr != nullptr) {
AddTraceMe("MemoryAllocation", ptr);
return ptr;
}
// Try to extend
if (Extend(unused_alignment, rounded_bytes)) {
ptr = FindChunkPtr(bin_num, rounded_bytes, num_bytes, freed_before);
if (ptr != nullptr) {
AddTraceMe("MemoryAllocation", ptr);
return ptr;
}
}
if ((freed_before == 0) && (!timestamped_chunks_.empty())) {
// We're unable to satisfy an allocation request without a specific
// timestamp requirement. Rather than fail, try merging any held-out
// timestamped chunks more aggressively until a free chunk of the necessary
// size is formed.
if (MergeTimestampedChunks(rounded_bytes)) {
ptr = FindChunkPtr(bin_num, rounded_bytes, num_bytes, freed_before);
if (ptr != nullptr) {
AddTraceMe("MemoryAllocation", ptr);
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
// the unallocated bytes and form a larger region.
if (DeallocateFreeRegions(rounded_bytes) &&
Extend(unused_alignment, rounded_bytes)) {
ptr = FindChunkPtr(bin_num, rounded_bytes, num_bytes, freed_before);
if (ptr != nullptr) {
AddTraceMe("MemoryAllocation", ptr);
return ptr;
}
}
// We searched all bins for an existing free chunk to use and
// couldn't find one. This means we must have run out of memory,
// Dump the memory log for analysis.
MaybeWriteMemoryMap();
if (dump_log_on_failure) {
LOG(WARNING)
<< "Allocator (" << Name() << ") ran out of memory trying "
<< "to allocate " << strings::HumanReadableNumBytes(num_bytes)
<< " (rounded to " << rounded_bytes << ")"
<< "requested by op "
<< ScopedMemoryDebugAnnotation::CurrentAnnotation().pending_op_name
<< "\nCurrent allocation summary follows.";
DumpMemoryLog(rounded_bytes);
LOG(WARNING) << RenderOccupancy();
}
return nullptr;
}
int64 BFCAllocator::LargestFreeChunk() {
for (int i = kNumBins - 1; i >= 0; i--) {
if (!BinFromIndex(i)->free_chunks.empty()) {
return ChunkFromHandle(*BinFromIndex(i)->free_chunks.rbegin())->size;
}
}
return 0;
}
double BFCAllocator::GetFragmentation() {
int64 bytes_available = total_region_allocated_bytes_ - stats_.bytes_in_use;
DCHECK_GT(bytes_available, 0);
return static_cast<double>(bytes_available - LargestFreeChunk()) /
bytes_available;
}
void BFCAllocator::AddTraceMe(absl::string_view traceme_name, const void* ptr) {
BFCAllocator::Chunk* chunk = ChunkFromHandle(region_manager_.get_handle(ptr));
AddTraceMe(traceme_name, chunk->ptr, chunk->requested_size, chunk->size);
}
void BFCAllocator::AddTraceMe(absl::string_view traceme_name,
const void* chunk_ptr, int64 req_bytes,
int64 alloc_bytes) {
tensorflow::profiler::TraceMe::InstantActivity(
[this, traceme_name, chunk_ptr, req_bytes,
alloc_bytes]() TF_NO_THREAD_SAFETY_ANALYSIS {
int64 bytes_available =
memory_limit_ - stats_.bytes_reserved - stats_.bytes_in_use;
const auto& annotation =
ScopedMemoryDebugAnnotation::CurrentAnnotation();
std::string tensor_shape;
if (annotation.pending_shape) {
tensor_shape = annotation.pending_shape->DebugString();
}
return tensorflow::profiler::TraceMeEncode(
traceme_name, {{"allocator_name", name_},
{"bytes_reserved", stats_.bytes_reserved},
{"bytes_allocated", stats_.bytes_in_use},
{"bytes_available", bytes_available},
{"fragmentation", GetFragmentation()},
{"peak_bytes_in_use", stats_.peak_bytes_in_use},
{"requested_bytes", req_bytes},
{"allocation_bytes", alloc_bytes},
{"addr", reinterpret_cast<uint64>(chunk_ptr)},
{"tf_op", annotation.pending_op_name},
{"id", annotation.pending_step_id},
{"region_type", annotation.pending_region_type},
{"data_type", annotation.pending_data_type},
{"shape", tensor_shape}});
},
/*level=*/profiler::TraceMeLevel::kInfo);
}
void* BFCAllocator::FindChunkPtr(BinNum bin_num, size_t rounded_bytes,
size_t num_bytes, uint64 freed_before) {
// First identify the first bin that could satisfy rounded_bytes.
for (; bin_num < kNumBins; bin_num++) {
// Start searching from the first bin for the smallest chunk that fits
// rounded_bytes.
Bin* b = BinFromIndex(bin_num);
for (auto citer = b->free_chunks.begin(); citer != b->free_chunks.end();
++citer) {
const BFCAllocator::ChunkHandle h = (*citer);
BFCAllocator::Chunk* chunk = ChunkFromHandle(h);
DCHECK(!chunk->in_use());
if (freed_before > 0 && freed_before < chunk->freed_at_count) {
continue;
}
if (chunk->size >= rounded_bytes) {
// We found an existing chunk that fits us that wasn't in use, so remove
// it from the free bin structure prior to using.
RemoveFreeChunkIterFromBin(&b->free_chunks, citer);
// If we can break the size of the chunk into two reasonably large
// pieces, do so. In any case don't waste more than
// kMaxInternalFragmentation bytes on padding this alloc.
const int64 kMaxInternalFragmentation = 128 << 20; // 128mb
if (chunk->size >= rounded_bytes * 2 ||
static_cast<int64>(chunk->size) - rounded_bytes >=
kMaxInternalFragmentation) {
SplitChunk(h, rounded_bytes);
chunk = ChunkFromHandle(h); // Update chunk pointer in case it moved
}
// The requested size of the returned chunk is what the user
// has allocated.
chunk->requested_size = num_bytes;
// Assign a unique id and increment the id counter, marking the
// chunk as being in use.
chunk->allocation_id = next_allocation_id_++;
// Update stats.
++stats_.num_allocs;
stats_.bytes_in_use += chunk->size;
stats_.peak_bytes_in_use =
std::max(stats_.peak_bytes_in_use, stats_.bytes_in_use);
stats_.largest_alloc_size =
std::max<std::size_t>(stats_.largest_alloc_size, chunk->size);
#ifdef TENSORFLOW_MEM_DEBUG
if (ShouldRecordOpName()) {
const auto& annotation =
ScopedMemoryDebugAnnotation::CurrentAnnotation();
if (annotation.pending_op_name != nullptr) {
chunk->op_name = annotation.pending_op_name;
} else {
LOG(INFO) << "missing pending_op_name for " << Name()
<< " reading addr "
<< static_cast<const void*>(&annotation.pending_op_name)
<< "\n"
<< CurrentStackTrace();
chunk->op_name = nullptr;
}
chunk->action_count = ++action_counter_;
chunk->step_id = annotation.pending_step_id;
int slot = chunk->action_count % MEM_DEBUG_SIZE_HISTORY_SIZE;
size_history_[slot] = stats_.bytes_in_use;
}
#endif
VLOG(4) << "Returning: " << chunk->ptr;
if (VLOG_IS_ON(4)) {
LOG(INFO) << "A: " << RenderOccupancy();
}
return chunk->ptr;
}
}
}
return nullptr;
}
void BFCAllocator::SplitChunk(BFCAllocator::ChunkHandle h, size_t num_bytes) {
// Allocate the new chunk before we do any ChunkFromHandle
ChunkHandle h_new_chunk = AllocateChunk();
Chunk* c = ChunkFromHandle(h);
CHECK(!c->in_use() && (c->bin_num == kInvalidBinNum));
// Create a new chunk starting num_bytes after c
BFCAllocator::Chunk* new_chunk = ChunkFromHandle(h_new_chunk);
new_chunk->ptr = static_cast<void*>(static_cast<char*>(c->ptr) + num_bytes);
region_manager_.set_handle(new_chunk->ptr, h_new_chunk);
// Set the new sizes of the chunks.
new_chunk->size = c->size - num_bytes;
c->size = num_bytes;
// The new chunk is not in use.
new_chunk->allocation_id = -1;
// It inherits the freed time.
new_chunk->freed_at_count = c->freed_at_count;
// Maintain the pointers.
// c <-> c_neighbor becomes
// c <-> new_chunk <-> c_neighbor
BFCAllocator::ChunkHandle h_neighbor = c->next;
new_chunk->prev = h;
new_chunk->next = h_neighbor;
c->next = h_new_chunk;
if (h_neighbor != kInvalidChunkHandle) {
Chunk* c_neighbor = ChunkFromHandle(h_neighbor);
c_neighbor->prev = h_new_chunk;
}
// Add the newly free chunk to the free bin.
InsertFreeChunkIntoBin(h_new_chunk);
}
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;
}
mutex_lock l(lock_);
// Find the chunk from the ptr.
BFCAllocator::ChunkHandle h = region_manager_.get_handle(ptr);
CHECK(h != kInvalidChunkHandle);
// Record chunk information before it's freed.
Chunk* chunk = ChunkFromHandle(h);
void* chunk_ptr = chunk->ptr;
int64 req_bytes = chunk->requested_size;
int64 alloc_bytes = chunk->size;
MarkFree(h);
// Consider coalescing it.
if (timing_counter_) {
InsertFreeChunkIntoBin(h);
timestamped_chunks_.push_back(h);
} else {
InsertFreeChunkIntoBin(TryToCoalesce(h, false));
}
// TraceMe needs to be added after MarkFree and InsertFreeChunkIntoBin for
// correct aggregation stats (bytes_in_use, fragmentation).
AddTraceMe("MemoryDeallocation", chunk_ptr, req_bytes, alloc_bytes);
if (VLOG_IS_ON(4)) {
LOG(INFO) << "F: " << RenderOccupancy();
}
}
// Merges h1 and h2 when Chunk(h1)->next is h2 and Chunk(h2)->prev is c1.
// We merge Chunk(h2) into Chunk(h1).
void BFCAllocator::Merge(BFCAllocator::ChunkHandle h1,
BFCAllocator::ChunkHandle h2) {
Chunk* c1 = ChunkFromHandle(h1);
Chunk* c2 = ChunkFromHandle(h2);
// We can only merge chunks that are not in use.
CHECK(!c1->in_use() && !c2->in_use());
// c1's prev doesn't change, still points to the same ptr, and is
// still not in use.
// Fix up neighbor pointers
//
// c1 <-> c2 <-> c3 should become
// c1 <-> c3
BFCAllocator::ChunkHandle h3 = c2->next;
c1->next = h3;
CHECK(c2->prev == h1);
if (h3 != kInvalidChunkHandle) {
BFCAllocator::Chunk* c3 = ChunkFromHandle(h3);
c3->prev = h1;
}
// Set the new size
c1->size += c2->size;
// Pick latest free time.
c1->freed_at_count = std::max(c1->freed_at_count, c2->freed_at_count);
DeleteChunk(h2);
}
void BFCAllocator::DeleteChunk(ChunkHandle h) {
// Delete h and cleanup all state
Chunk* c = ChunkFromHandle(h);
// VLOG(4) << "Removing: " << c->ptr;
region_manager_.erase(c->ptr);
DeallocateChunk(h);
}
void BFCAllocator::InsertFreeChunkIntoBin(BFCAllocator::ChunkHandle h) {
Chunk* c = ChunkFromHandle(h);
CHECK(!c->in_use() && (c->bin_num == kInvalidBinNum));
BinNum bin_num = BinNumForSize(c->size);
Bin* new_bin = BinFromIndex(bin_num);
c->bin_num = bin_num;
new_bin->free_chunks.insert(h);
}
void BFCAllocator::RemoveFreeChunkIterFromBin(
BFCAllocator::Bin::FreeChunkSet* free_chunks,
const BFCAllocator::Bin::FreeChunkSet::iterator& citer) {
ChunkHandle h = *citer;
Chunk* c = ChunkFromHandle(h);
CHECK(!c->in_use() && (c->bin_num != kInvalidBinNum));
free_chunks->erase(citer);
c->bin_num = kInvalidBinNum;
}
void BFCAllocator::RemoveFreeChunkFromBin(BFCAllocator::ChunkHandle h) {
Chunk* c = ChunkFromHandle(h);
CHECK(!c->in_use() && (c->bin_num != kInvalidBinNum));
CHECK_GT(BinFromIndex(c->bin_num)->free_chunks.erase(h), 0)
<< "Could not find chunk in bin";
c->bin_num = kInvalidBinNum;
}
void BFCAllocator::MarkFree(BFCAllocator::ChunkHandle h) {
Chunk* c = ChunkFromHandle(h);
CHECK(c->in_use() && (c->bin_num == kInvalidBinNum));
// Mark the chunk as no longer in use.
c->allocation_id = -1;
// Optionally record the free time.
if (timing_counter_) {
c->freed_at_count = timing_counter_->next();
}
// Updates the stats.
stats_.bytes_in_use -= c->size;
#ifdef TENSORFLOW_MEM_DEBUG
if (ShouldRecordOpName()) {
c->action_count = ++action_counter_;
int slot = c->action_count % MEM_DEBUG_SIZE_HISTORY_SIZE;
size_history_[slot] = stats_.bytes_in_use;
}
#endif
}
BFCAllocator::ChunkHandle BFCAllocator::TryToCoalesce(ChunkHandle h,
bool ignore_freed_at) {
Chunk* c = ChunkFromHandle(h);
if ((!ignore_freed_at) && c->freed_at_count > 0) return h;
ChunkHandle coalesced_chunk = h;
// If the next chunk is free, merge it into c and delete it.
if (c->next != kInvalidChunkHandle && !ChunkFromHandle(c->next)->in_use()) {
Chunk* n = ChunkFromHandle(c->next);
if ((n->freed_at_count == 0) || ignore_freed_at) {
VLOG(4) << "Merging c->next " << n->ptr << " with c " << c->ptr;
RemoveFreeChunkFromBin(c->next);
Merge(h, c->next);
}
}
// If the previous chunk is free, merge c into it and delete c.
if (c->prev != kInvalidChunkHandle && !ChunkFromHandle(c->prev)->in_use()) {
Chunk* n = ChunkFromHandle(c->prev);
if ((n->freed_at_count == 0) || ignore_freed_at) {
VLOG(4) << "Merging c " << c->ptr << " into c->prev " << n->ptr;
coalesced_chunk = c->prev;
RemoveFreeChunkFromBin(c->prev);
Merge(c->prev, h);
}
}
return coalesced_chunk;
}
void BFCAllocator::SetSafeFrontier(uint64 count) {
uint64 current = safe_frontier_.load(std::memory_order_relaxed);
while (count > current) {
if (safe_frontier_.compare_exchange_strong(current, count)) {
retry_helper_.NotifyDealloc();
return;
} else {
current = safe_frontier_.load(std::memory_order_relaxed);
}
}
}
bool BFCAllocator::MergeTimestampedChunks(size_t required_bytes) {
VLOG(1) << "MergeTimestampedChunks queue_len=" << timestamped_chunks_.size()
<< " required_bytes=" << required_bytes;
bool satisfied = (required_bytes == 0);
std::vector<void*> to_merge;
std::deque<ChunkHandle> new_ts_queue;
while (!timestamped_chunks_.empty()) {
ChunkHandle h = timestamped_chunks_.front();
timestamped_chunks_.pop_front();
DCHECK_NE(h, kInvalidChunkHandle);
Chunk* c = ChunkFromHandle(h);
// It's possible this chunk has already been merged so refetch and retest
// the handle.
h = region_manager_.get_handle(c->ptr);
if (h == kInvalidChunkHandle) {
continue;
}
if (c->in_use() || (c->bin_num == kInvalidBinNum)) {
// This chunk has already been reallocated.
continue;
}
if (c->freed_at_count == 0) {
to_merge.push_back(c->ptr);
continue;
}
// Chunk should be free and assigned to a bin.
DCHECK_NE(c->bin_num, kInvalidBinNum);
if (c->freed_at_count < safe_frontier_) {
c->freed_at_count = 0;
to_merge.push_back(c->ptr);
} else if (required_bytes > 0) {
to_merge.push_back(c->ptr);
} else {
new_ts_queue.push_back(h);
}
}
DCHECK(timestamped_chunks_.empty());
std::swap(timestamped_chunks_, new_ts_queue);
// At this point all candidate chunks have been moved from timestamped_chunks_
// to to_merge. If this is a standard merge (required_bytes == 0) then
// merge them all, otherwise merge just until a Chunk of the required size
// is produced.
for (int ci = 0; ci < to_merge.size(); ++ci) {
void* ptr = to_merge[ci];
// It's possible that the Chunk associated with this memory location got
// merged and deallocated in a prior iteration so refetch the handle and
// retest.
ChunkHandle h = region_manager_.get_handle(ptr);
if (h == kInvalidChunkHandle) continue;
if (required_bytes == 0 || !satisfied) {
Chunk* c = ChunkFromHandle(h);
DCHECK_NE(c->bin_num, kInvalidBinNum);
DCHECK(!c->in_use());
RemoveFreeChunkFromBin(h);
ChunkHandle new_h = TryToCoalesce(h, (required_bytes > 0));
InsertFreeChunkIntoBin(new_h);
if (required_bytes > 0) {
c = ChunkFromHandle(new_h);
if (new_h != h && c->freed_at_count > 0) {
timestamped_chunks_.push_back(new_h);
}
if (c->size >= required_bytes) {
satisfied = true;
}
}
} else {
// We were force merging Chunks with unsafe timestamps, but managed
// to create a satisfying Chunk so just requeue the rest.
timestamped_chunks_.push_back(h);
}
}
return satisfied;
}
bool BFCAllocator::TracksAllocationSizes() const { return true; }
size_t BFCAllocator::RequestedSize(const void* ptr) const {
CHECK(ptr);
mutex_lock l(lock_);
BFCAllocator::ChunkHandle h = region_manager_.get_handle(ptr);
CHECK(h != kInvalidChunkHandle)
<< "Asked for requested size of pointer we never allocated: " << ptr;
const BFCAllocator::Chunk* c = ChunkFromHandle(h);
return c->requested_size;
}
size_t BFCAllocator::AllocatedSize(const void* ptr) const {
mutex_lock l(lock_);
BFCAllocator::ChunkHandle h = region_manager_.get_handle(ptr);
CHECK(h != kInvalidChunkHandle)
<< "Asked for allocated size of pointer we never allocated: " << ptr;
const BFCAllocator::Chunk* c = ChunkFromHandle(h);
return c->size;
}
int64 BFCAllocator::AllocationId(const void* ptr) const {
mutex_lock l(lock_);
BFCAllocator::ChunkHandle h = region_manager_.get_handle(ptr);
CHECK(h != kInvalidChunkHandle)
<< "Asked for allocation id of pointer we never allocated: " << ptr;
const BFCAllocator::Chunk* c = ChunkFromHandle(h);
return c->allocation_id;
}
namespace {
void RenderRegion(char* rendered, const size_t resolution,
const size_t total_render_size, const size_t offset,
const void* base_ptr, const void* ptr, const size_t size,
const char c) {
const char* base_ptr_c = static_cast<const char*>(base_ptr);
const char* ptr_c = static_cast<const char*>(ptr);
size_t start_location =
((ptr_c - base_ptr_c + offset) * resolution) / total_render_size;
CHECK_GE(start_location, 0);
CHECK_LT(start_location, resolution);
size_t end_location =
((ptr_c + size - 1 - base_ptr_c + offset) * resolution) /
total_render_size;
CHECK_GE(end_location, 0);
CHECK_LT(end_location, resolution);
for (size_t i = start_location; i <= end_location; ++i) {
rendered[i] = c;
}
}
} // namespace
string BFCAllocator::RenderOccupancy() {
// Make a buffer for the ASCII-art representation.
const size_t resolution = 100;
char rendered[resolution];
// Compute the total region size to render over
size_t total_region_size = 0;
for (const auto& region : region_manager_.regions()) {
total_region_size += region.memory_size();
}
if (total_region_size == 0) {
return "<allocator contains no memory>";
}
// Start out with everything empty
RenderRegion(rendered, resolution, total_region_size, 0, nullptr, nullptr,
total_region_size, '_');
size_t region_offset = 0;
for (const auto& region : region_manager_.regions()) {
ChunkHandle h = region_manager_.get_handle(region.ptr());
// Then render each chunk left to right.
while (h != kInvalidChunkHandle) {
Chunk* c = ChunkFromHandle(h);
if (c->in_use()) {
// Render the wasted space
size_t wasted = c->size - c->requested_size;
if (wasted > 0) {
RenderRegion(rendered, resolution, total_region_size,
region_offset + c->requested_size, region.ptr(), c->ptr,
wasted, 'x');
}
// Then the occupied space
RenderRegion(rendered, resolution, total_region_size, region_offset,
region.ptr(), c->ptr, c->requested_size, '*');
}
h = c->next;
}
region_offset += region.memory_size();
}
return string(rendered, resolution);
}
void BFCAllocator::DumpMemoryLog(size_t num_bytes) {
const std::array<BinDebugInfo, kNumBins> bin_infos = get_bin_debug_info();
LOG(INFO) << "BFCAllocator dump for " << Name();
for (BinNum bin_num = 0; bin_num < kNumBins; bin_num++) {
Bin* b = BinFromIndex(bin_num);
const BinDebugInfo& bin_info = bin_infos[bin_num];
CHECK_EQ(b->free_chunks.size(),
bin_info.total_chunks_in_bin - bin_info.total_chunks_in_use);
LOG(INFO) << "Bin (" << b->bin_size
<< "): \tTotal Chunks: " << bin_info.total_chunks_in_bin
<< ", Chunks in use: " << bin_info.total_chunks_in_use << ". "
<< strings::HumanReadableNumBytes(bin_info.total_bytes_in_bin)
<< " allocated for chunks. "
<< strings::HumanReadableNumBytes(bin_info.total_bytes_in_use)
<< " in use in bin. "
<< strings::HumanReadableNumBytes(
bin_info.total_requested_bytes_in_use)
<< " client-requested in use in bin.";
}
// Find the bin that we would have liked to allocate in, so we
// can get some further analysis about fragmentation.
Bin* b = BinForSize(num_bytes);
LOG(INFO) << "Bin for " << strings::HumanReadableNumBytes(num_bytes)
<< " was " << strings::HumanReadableNumBytes(b->bin_size)
<< ", Chunk State: ";
for (ChunkHandle h : b->free_chunks) {
Chunk* c = ChunkFromHandle(h);
LOG(INFO) << c->DebugString(this, true);
}