BlockManager.cc 8.22 KB
Newer Older
Li Zhang's avatar
Li Zhang committed
1
2
3
4
5
6
// Copyright (c) OpenMMLab. All rights reserved.

#include "src/turbomind/models/llama/BlockManager.h"
#include "src/turbomind/utils/cuda_utils.h"
#include "src/turbomind/utils/debug_utils.h"
#include "src/turbomind/utils/logger.h"
Li Zhang's avatar
Li Zhang committed
7
#include "src/turbomind/utils/string_utils.h"
Li Zhang's avatar
Li Zhang committed
8
9
10
11
12
13
#include <algorithm>
#include <iterator>
#include <stdexcept>

namespace turbomind {

zhouxiang's avatar
zhouxiang committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
size_t GetSyncFreeMemSize(Barrier& barrier, std::atomic<size_t>& value)
{
    size_t free{};
    size_t total{};
    check_cuda_error(cudaMemGetInfo(&free, &total));

    // atomicMin
    auto old = value.load();
    while (old > free && !value.compare_exchange_weak(old, free)) {}

    // wait for all ranks
    barrier.wait();

    return value.load();
}

BlockManager::BlockManager(
    size_t block_size, double block_count, int chunk_size, IAllocator* allocator, GetFreeMemSize get_free_size):
Li Zhang's avatar
Li Zhang committed
32
33
34
    block_size_(block_size), allocator_(allocator)
{
    if (block_count < 1.) {
zhouxiang's avatar
zhouxiang committed
35
        max_block_count_ = GetBlockCount(block_size, block_count, get_free_size);
Li Zhang's avatar
Li Zhang committed
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
    }
    else {
        max_block_count_ = block_count;
    }

    if (chunk_size == 0) {
        chunk_size_ = static_cast<int>(std::sqrt(max_block_count_));
    }
    else if (chunk_size < 0) {
        chunk_size_ = max_block_count_;
    }
    else {
        chunk_size_ = chunk_size;
    }

    TM_LOG_INFO("[BlockManager] block_size = %lu MB", (unsigned long)block_size_ >> 20);
    TM_LOG_INFO("[BlockManager] max_block_count = %d", max_block_count_);
    TM_LOG_INFO("[BlockManager] chunk_size = %d", chunk_size_);

    blocks_.reserve(max_block_count_);

    active_ids_.reserve(max_block_count_);
    cached_ids_.reserve(max_block_count_);
    free_ids_.reserve(max_block_count_);

    // pre-allocate first chunk
    Malloc();
    dbg(free_ids_);
}

BlockManager::~BlockManager()
{
    for (auto& chunk : chunks_) {
        allocator_->free(&chunk);
    }
}

bool BlockManager::Malloc()
{
    auto chunk_size = std::min<int>(chunk_size_, max_block_count_ - blocks_.size());

    if (!chunk_size) {
        return false;
    }

gaoqiong's avatar
gaoqiong committed
81
    //auto ptr = (std::byte*)allocator_->malloc(block_size_ * chunk_size);
82
    auto ptr = (uint8_t*)allocator_->malloc(block_size_ * chunk_size);
Li Zhang's avatar
Li Zhang committed
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
    if (!ptr) {
        return false;
    }

    chunks_.push_back(ptr);

    for (int i = 0; i < chunk_size; ++i, ptr += block_size_) {
        auto& block     = blocks_.emplace_back();
        block.use_count = 0;
        block.id        = (int)blocks_.size() - 1;
        block.timestamp = 0;
        block.data      = ptr;

        free_ids_.push_back(block.id);
    }

    return true;
}

zhouxiang's avatar
zhouxiang committed
102
size_t BlockManager::GetBlockCount(size_t block_size, double ratio, GetFreeMemSize get_free_size)
Li Zhang's avatar
Li Zhang committed
103
{
zhouxiang's avatar
zhouxiang committed
104
105
    size_t free = get_free_size();
    return static_cast<size_t>(free * ratio) / block_size;
Li Zhang's avatar
Li Zhang committed
106
107
108
109
}

void BlockManager::Move(std::vector<int>& src, const std::vector<int>& delta, std::vector<int>& dst)
{
Li Zhang's avatar
Li Zhang committed
110
    FT_CHECK(src.size() >= delta.size());
Li Zhang's avatar
Li Zhang committed
111
    std::vector<int> src1(src.size() - delta.size());
Li Zhang's avatar
Li Zhang committed
112
113
114
115
    {
        auto end = std::set_difference(src.begin(), src.end(), delta.begin(), delta.end(), src1.begin());
        FT_CHECK(end == src1.end());
    }
Li Zhang's avatar
Li Zhang committed
116
117
118
    src.swap(src1);

    std::vector<int> dst1(dst.size() + delta.size());
Li Zhang's avatar
Li Zhang committed
119
120
121
122
    {
        auto end = std::set_union(dst.begin(), dst.end(), delta.begin(), delta.end(), dst1.begin());
        FT_CHECK(end == dst1.end());
    }
Li Zhang's avatar
Li Zhang committed
123
124
125
    dst.swap(dst1);
}

Li Zhang's avatar
Li Zhang committed
126
auto BlockManager::Allocate(int count) -> std::pair<BlockIds, UniqueIds>
Li Zhang's avatar
Li Zhang committed
127
128
129
130
131
132
133
{
    while (free_ids_.size() < count) {
        if (!Malloc()) {
            throw std::runtime_error("out of memory");
        }
    }

Li Zhang's avatar
Li Zhang committed
134
135
    BlockIds  block_ids(count);
    UniqueIds unique_ids(count);
Li Zhang's avatar
Li Zhang committed
136
137

    for (int i = 0; i < count; ++i) {
Li Zhang's avatar
Li Zhang committed
138
139
140
141
142
143
144
145
        int   idx = free_ids_[i];
        auto& b   = blocks_[idx];
        FT_CHECK(is_free(b));  // pre-condition: uc == 0 && ts == 0
        b.use_count = 1;
        b.unique_id = unique_id_++;
        FT_CHECK(is_active(b));  // post-condition
        block_ids[i]  = idx;
        unique_ids[i] = b.unique_id;
Li Zhang's avatar
Li Zhang committed
146
147
    }

Li Zhang's avatar
Li Zhang committed
148
    Move(free_ids_, block_ids, active_ids_);
Li Zhang's avatar
Li Zhang committed
149
150
151

    dbg(free_ids_, active_ids_);

Li Zhang's avatar
Li Zhang committed
152
    return {block_ids, unique_ids};
Li Zhang's avatar
Li Zhang committed
153
154
155
156
}

void BlockManager::Evict(int count)
{
Li Zhang's avatar
Li Zhang committed
157
    FT_CHECK(count <= cached_ids_.size());
Li Zhang's avatar
Li Zhang committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
    std::vector<int> idxs(cached_ids_);
    // get first `count` cached ids according to timestamp
    std::nth_element(idxs.begin(), idxs.begin() + count, idxs.end(), [&](int i, int j) {
        return blocks_[i].timestamp < blocks_[j].timestamp;
    });
    idxs.resize(count);

    // sort the retrieved ids
    std::sort(idxs.begin(), idxs.end());

    // set as free
    for (const auto& idx : idxs) {
        auto& b = blocks_[idx];
        FT_CHECK(is_cached(b));
        b.unique_id = 0;
        b.timestamp = 0;
Li Zhang's avatar
Li Zhang committed
174
        FT_CHECK(is_free(b));
Li Zhang's avatar
Li Zhang committed
175
176
177
178
179
180
181
    }

    Move(cached_ids_, idxs, free_ids_);

    dbg(cached_ids_, free_ids_);
}

Li Zhang's avatar
Li Zhang committed
182
void BlockManager::Free(BlockIds ids)
Li Zhang's avatar
Li Zhang committed
183
{
Li Zhang's avatar
Li Zhang committed
184
    std::sort(ids.begin(), ids.end());
Li Zhang's avatar
Li Zhang committed
185

Li Zhang's avatar
Li Zhang committed
186
187
188
189
190
191
    for (const auto& i : ids) {
        auto& b = blocks_[i];
        FT_CHECK(is_cached(b));  // uc == 0 && ts != 0
        b.unique_id = 0;
        b.timestamp = 0;
        FT_CHECK(is_free(b));
Li Zhang's avatar
Li Zhang committed
192
193
    }

Li Zhang's avatar
Li Zhang committed
194
    Move(cached_ids_, ids, free_ids_);
Li Zhang's avatar
Li Zhang committed
195
196
}

Li Zhang's avatar
Li Zhang committed
197
int BlockManager::Unlock(const BlockIds& ids)
Li Zhang's avatar
Li Zhang committed
198
{
Li Zhang's avatar
Li Zhang committed
199
200
201
202
203
204
205
206
207
    BlockIds unlock;
    unlock.reserve(ids.size());

    for (const auto& i : ids) {
        auto& b = blocks_[i];
        FT_CHECK(is_active(b));  // pre-condition: uc > 0
        if (--b.use_count == 0) {
            unlock.push_back(b.id);
            FT_CHECK(is_cached(b));  // post-condition
Li Zhang's avatar
Li Zhang committed
208
209
210
        }
    }

Li Zhang's avatar
Li Zhang committed
211
    std::sort(unlock.begin(), unlock.end());
Li Zhang's avatar
Li Zhang committed
212

Li Zhang's avatar
Li Zhang committed
213
    Move(active_ids_, unlock, cached_ids_);
Li Zhang's avatar
Li Zhang committed
214
215

    dbg(active_ids_, cached_ids_);
Li Zhang's avatar
Li Zhang committed
216
    return unlock.size();
Li Zhang's avatar
Li Zhang committed
217
218
}

Li Zhang's avatar
Li Zhang committed
219
int BlockManager::Lock(const BlockIds& ids)
Li Zhang's avatar
Li Zhang committed
220
{
Li Zhang's avatar
Li Zhang committed
221
222
    BlockIds lock;
    lock.reserve(ids.size());
Li Zhang's avatar
Li Zhang committed
223

Li Zhang's avatar
Li Zhang committed
224
225
    for (const auto& i : ids) {
        auto& b = blocks_[i];
Li Zhang's avatar
Li Zhang committed
226
        FT_CHECK_WITH_INFO(is_cached(b), to_string(b));
Li Zhang's avatar
Li Zhang committed
227
228
229
        if (++b.use_count == 1) {
            lock.push_back(i);
            FT_CHECK(is_active(b));
Li Zhang's avatar
Li Zhang committed
230
231
232
        }
    }

Li Zhang's avatar
Li Zhang committed
233
    std::sort(lock.begin(), lock.end());
Li Zhang's avatar
Li Zhang committed
234

Li Zhang's avatar
Li Zhang committed
235
    Move(cached_ids_, lock, active_ids_);
Li Zhang's avatar
Li Zhang committed
236
237
238

    // dbg(cached_ids_, active_ids_);

Li Zhang's avatar
Li Zhang committed
239
    return lock.size();
Li Zhang's avatar
Li Zhang committed
240
241
}

Li Zhang's avatar
Li Zhang committed
242
void BlockManager::Touch(const BlockIds& ids)
Li Zhang's avatar
Li Zhang committed
243
{
Li Zhang's avatar
Li Zhang committed
244
245
246
    std::for_each(ids.crbegin(), ids.crend(), [this](int i) {
        FT_CHECK(is_active(blocks_[i]));
        blocks_[i].timestamp = timestamp_++;
Li Zhang's avatar
Li Zhang committed
247
248
249
    });
}

Li Zhang's avatar
Li Zhang committed
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
int BlockManager::Verify(const std::vector<int>& block_ids, const std::vector<uint64_t>& unique_ids)
{
    FT_CHECK(block_ids.size() == unique_ids.size());
    int valid = block_ids.size();
    for (int i = 0; i < block_ids.size(); ++i) {
        if (unique_id(block_ids[i]) != unique_ids[i]) {
            valid = i;
            break;
        }
    }
    int miss = 0;
    for (int i = valid; i < block_ids.size(); ++i) {
        miss += (unique_id(block_ids[i]) != unique_ids[i]);
    }
    // All later blocks should have been invalidated
    FT_CHECK_WITH_INFO(miss == (int)block_ids.size() - valid,
                       fmtstr("count = %d, valid = %d, miss = %d", (int)block_ids.size(), valid, miss));
    return valid;
}

Li Zhang's avatar
Li Zhang committed
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
Snapshot BlockManager::TakeSnapshot()
{
    std::vector<int> use_count(blocks_.size());
    for (const auto& idx : active_ids_) {
        use_count[idx] = blocks_[idx].use_count;
    }
    return {active_count(), cached_count(), free_count(), std::move(use_count)};
}

std::ostream& operator<<(std::ostream& os, const BlockManager& manager)
{
    os << "block_size: " << manager.block_size_ << ", ";
    os << "max_block_count: " << manager.max_block_count_ << ", ";
    os << "chunk_size: " << manager.chunk_size_ << ", ";
    os << "chunks: " << manager.chunks_.size() << ", ";
    os << "active_ids: " << manager.active_ids_.size() << ", ";
    os << "cached_ids: " << manager.cached_ids_.size() << ", ";
    os << "free_ids: " << manager.free_ids_.size() << ", ";
    os << "blocks: " << manager.blocks_.size() << ", ";
    os << "unique_id: " << manager.unique_id_ << ", ";
    os << "timestamp: " << manager.timestamp_ << ", ";
    os << "allocator: " << manager.allocator_;
    return os;
}

std::ostream& operator<<(std::ostream& os, const Block& block)
{
    os << "id=" << block.id << ", use_count=" << block.use_count << ", unique_id=" << block.unique_id
       << ", timestamp=" << block.timestamp << ", data=" << block.data;
    return os;
}

}  // namespace turbomind