aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/compiler/xla/service/gpu/buffer_allocations.cc
blob: b095d4cd731bb7877baffbf69cb17bd50e101d6b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/xla/service/gpu/buffer_allocations.h"

#include <utility>

#include "tensorflow/compiler/xla/map_util.h"
#include "tensorflow/compiler/xla/ptr_util.h"
#include "tensorflow/compiler/xla/service/gpu/gpu_constants.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"

namespace xla {
namespace gpu {

void BufferAllocations::Builder::RegisterBuffer(BufferAllocation::Index index,
                                                se::DeviceMemoryBase address) {
  InsertOrDie(&registered_buffers_, index, address);
}

StatusOr<std::unique_ptr<BufferAllocations>> BufferAllocations::Builder::Build(
    const BufferAssignment* buffer_assignment, int device_ordinal,
    DeviceMemoryAllocator* memory_allocator) {
  const int64 num_buffers = buffer_assignment->Allocations().size();
  auto buffer_allocations = WrapUnique(new BufferAllocations(
      num_buffers, device_ordinal, memory_allocator, buffer_assignment));

  for (BufferAllocation::Index i = 0; i < num_buffers; ++i) {
    // If buffer #i's address is already registered (e.g. external arguments or
    // result buffers), use that registered buffer.
    if (registered_buffers_.count(i)) {
      se::DeviceMemoryBase address = FindOrDie(registered_buffers_, i);
      if (reinterpret_cast<uintptr_t>(address.opaque()) %
              kEntryParameterAlignBytes !=
          0) {
        return InternalError(
            "Address of registered buffer %lld must be a multiple of %llx, but "
            "was %p",
            i, kEntryParameterAlignBytes, address.opaque());
      }
      buffer_allocations->SetBuffer(i, FindOrDie(registered_buffers_, i));
      continue;
    }

    // Allocate each allocation that might escape, or is the temp buffer.
    bool seen_temp_buffer = false;
    const BufferAllocation& allocation = buffer_assignment->GetAllocation(i);
    if (allocation.maybe_live_out() || allocation.IsPreallocatedTempBuffer()) {
      const int64 buffer_size = allocation.size();
      se::DeviceMemoryBase buffer_address;
      if (buffer_size > 0) {
        OwningDeviceMemory buffer;
        TF_ASSIGN_OR_RETURN(
            buffer, memory_allocator->Allocate(device_ordinal, buffer_size));
        if (reinterpret_cast<uintptr_t>(buffer.opaque()) %
                kXlaAllocatedBufferAlignBytes !=
            0) {
          return InternalError(
              "Address returned by memory_allocator->Allocate must be a "
              "multiple of %llx, but was %p",
              kXlaAllocatedBufferAlignBytes, buffer.opaque());
        }
        // We do manual memory management within BufferAllocations.  Be sure not
        // to do a TF_RETURN_IF_ERROR between this line and the
        // buffer_allocations->SetBuffer(buffer_address) call below!
        buffer_address = buffer.Forget();
      }

      buffer_allocations->SetBuffer(i, buffer_address);
      if (allocation.IsPreallocatedTempBuffer()) {
        if (seen_temp_buffer) {
          LOG(FATAL) << "Multiple temporary buffers detected.  BufferAssigner "
                     << "must guarantee at most one temporary buffer.";
        }
        seen_temp_buffer = true;
        buffer_allocations->temp_buffer_base_ = buffer_address;
      }
    }
  }

  if (VLOG_IS_ON(2)) {
    for (BufferAllocation::Index i = 0; i < num_buffers; ++i) {
      const auto& buf = buffer_allocations->buffers_[i];
      VLOG(2) << "Buffer " << i << " -> " << buf.opaque() << " (" << buf.size()
              << "B)";
    }
  }
  return std::move(buffer_allocations);
}

BufferAllocations::~BufferAllocations() {
  if (!torn_down_) {
    // Presumably if we're executing this branch, the caller is in an error
    // state, otherwise it would have explicitly called TearDown so it could
    // save some set of live addresses.  So ignoring any errors in TearDown is
    // sensible.
    TearDown(/*live_addresses=*/{}).IgnoreError();
  }
}

Status BufferAllocations::TearDown(
    const std::set<se::DeviceMemoryBase>& live_addresses) {
  // Deallocate temporary buffers, taking care to try to deallocate all of them
  // even if one of the deallocations fails.
  Status status;
  const int64 num_buffers = buffer_assignment_->Allocations().size();
  for (BufferAllocation::Index i = 0; i < num_buffers; ++i) {
    const BufferAllocation& allocation = buffer_assignment_->GetAllocation(i);
    se::DeviceMemoryBase buffer_address = GetDeviceAddress(allocation.index());
    // Deallocate buffers marked "maybe_live_out" but aren't actually live out,
    // and temp buffers.
    if ((allocation.maybe_live_out() &&
         !live_addresses.count(buffer_address)) ||
        allocation.IsPreallocatedTempBuffer()) {
      auto dealloc_result =
          memory_allocator_->Deallocate(device_ordinal_, buffer_address);
      if (!dealloc_result.ok() && status.ok()) {
        status = dealloc_result;
      }
    }
  }
  torn_down_ = true;
  return status;
}

se::DeviceMemoryBase BufferAllocations::GetDeviceAddress(
    BufferAllocation::Index buffer_index) const {
  CHECK_GE(buffer_index, 0);
  CHECK_LT(buffer_index, buffers_.size());
  return buffers_[buffer_index];
}

se::DeviceMemoryBase BufferAllocations::GetDeviceAddress(
    const BufferAllocation::Slice& buffer_slice) const {
  se::DeviceMemoryBase base = GetDeviceAddress(buffer_slice.index());
  CHECK_LE(buffer_slice.offset(), base.size());
  CHECK_LE(buffer_slice.offset() + buffer_slice.size(), base.size());
  return se::DeviceMemoryBase(
      static_cast<char*>(base.opaque()) + buffer_slice.offset(),
      buffer_slice.size(), /*is_sub_buffer=*/true);
}

void BufferAllocations::SetBuffer(BufferAllocation::Index buffer_index,
                                  se::DeviceMemoryBase buffer) {
  CHECK_GE(buffer_index, 0);
  CHECK_LT(buffer_index, buffers_.size());
  buffers_[buffer_index] = buffer;
}

}  // namespace gpu
}  // namespace xla