BlockManager.cc 7.76 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
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
#include <algorithm>
#include <iterator>
#include <stdexcept>

namespace turbomind {

BlockManager::BlockManager(size_t block_size, double block_count, int chunk_size, IAllocator* allocator):
    block_size_(block_size), allocator_(allocator)
{
    if (block_count < 1.) {
        max_block_count_ = GetBlockCount(block_size, block_count);
    }
    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;
    }

    auto ptr = (std::byte*)allocator_->malloc(block_size_ * chunk_size);
    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;
}

size_t BlockManager::GetBlockCount(size_t block_size, double ratio)
{
    size_t free{};
    size_t total{};
    check_cuda_error(cudaMemGetInfo(&free, &total));
    return static_cast<size_t>(total * ratio) / block_size;
}

void BlockManager::Move(std::vector<int>& src, const std::vector<int>& delta, std::vector<int>& dst)
{
Li Zhang's avatar
Li Zhang committed
94
    FT_CHECK(src.size() >= delta.size());
Li Zhang's avatar
Li Zhang committed
95
    std::vector<int> src1(src.size() - delta.size());
Li Zhang's avatar
Li Zhang committed
96
97
98
99
    {
        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
100
101
102
    src.swap(src1);

    std::vector<int> dst1(dst.size() + delta.size());
Li Zhang's avatar
Li Zhang committed
103
104
105
106
    {
        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
107
108
109
    dst.swap(dst1);
}

Li Zhang's avatar
Li Zhang committed
110
auto BlockManager::Allocate(int count) -> std::pair<BlockIds, UniqueIds>
Li Zhang's avatar
Li Zhang committed
111
112
113
114
115
116
117
{
    while (free_ids_.size() < count) {
        if (!Malloc()) {
            throw std::runtime_error("out of memory");
        }
    }

Li Zhang's avatar
Li Zhang committed
118
119
    BlockIds  block_ids(count);
    UniqueIds unique_ids(count);
Li Zhang's avatar
Li Zhang committed
120
121

    for (int i = 0; i < count; ++i) {
Li Zhang's avatar
Li Zhang committed
122
123
124
125
126
127
128
129
        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
130
131
    }

Li Zhang's avatar
Li Zhang committed
132
    Move(free_ids_, block_ids, active_ids_);
Li Zhang's avatar
Li Zhang committed
133
134
135

    dbg(free_ids_, active_ids_);

Li Zhang's avatar
Li Zhang committed
136
    return {block_ids, unique_ids};
Li Zhang's avatar
Li Zhang committed
137
138
139
140
}

void BlockManager::Evict(int count)
{
Li Zhang's avatar
Li Zhang committed
141
    FT_CHECK(count <= cached_ids_.size());
Li Zhang's avatar
Li Zhang committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
    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
158
        FT_CHECK(is_free(b));
Li Zhang's avatar
Li Zhang committed
159
160
161
162
163
164
165
    }

    Move(cached_ids_, idxs, free_ids_);

    dbg(cached_ids_, free_ids_);
}

Li Zhang's avatar
Li Zhang committed
166
void BlockManager::Free(BlockIds ids)
Li Zhang's avatar
Li Zhang committed
167
{
Li Zhang's avatar
Li Zhang committed
168
    std::sort(ids.begin(), ids.end());
Li Zhang's avatar
Li Zhang committed
169

Li Zhang's avatar
Li Zhang committed
170
171
172
173
174
175
    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
176
177
    }

Li Zhang's avatar
Li Zhang committed
178
    Move(cached_ids_, ids, free_ids_);
Li Zhang's avatar
Li Zhang committed
179
180
}

Li Zhang's avatar
Li Zhang committed
181
int BlockManager::Unlock(const BlockIds& ids)
Li Zhang's avatar
Li Zhang committed
182
{
Li Zhang's avatar
Li Zhang committed
183
184
185
186
187
188
189
190
191
    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
192
193
194
        }
    }

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

Li Zhang's avatar
Li Zhang committed
197
    Move(active_ids_, unlock, cached_ids_);
Li Zhang's avatar
Li Zhang committed
198
199

    dbg(active_ids_, cached_ids_);
Li Zhang's avatar
Li Zhang committed
200
    return unlock.size();
Li Zhang's avatar
Li Zhang committed
201
202
}

Li Zhang's avatar
Li Zhang committed
203
int BlockManager::Lock(const BlockIds& ids)
Li Zhang's avatar
Li Zhang committed
204
{
Li Zhang's avatar
Li Zhang committed
205
206
    BlockIds lock;
    lock.reserve(ids.size());
Li Zhang's avatar
Li Zhang committed
207

Li Zhang's avatar
Li Zhang committed
208
209
210
211
212
213
    for (const auto& i : ids) {
        auto& b = blocks_[i];
        FT_CHECK(is_cached(b));
        if (++b.use_count == 1) {
            lock.push_back(i);
            FT_CHECK(is_active(b));
Li Zhang's avatar
Li Zhang committed
214
215
216
        }
    }

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

Li Zhang's avatar
Li Zhang committed
219
    Move(cached_ids_, lock, active_ids_);
Li Zhang's avatar
Li Zhang committed
220
221
222

    // dbg(cached_ids_, active_ids_);

Li Zhang's avatar
Li Zhang committed
223
    return lock.size();
Li Zhang's avatar
Li Zhang committed
224
225
}

Li Zhang's avatar
Li Zhang committed
226
void BlockManager::Touch(const BlockIds& ids)
Li Zhang's avatar
Li Zhang committed
227
{
Li Zhang's avatar
Li Zhang committed
228
229
230
    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
231
232
233
    });
}

Li Zhang's avatar
Li Zhang committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
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
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