#include "format/store_io.h" #include #include #include #include #include #include "common/base.h" #include "common/numeric.h" #include "common/threads.h" #include "format/safetensors.h" namespace hk { // reads are cut into pieces so that several are in flight at once static const int64_t kTrunkPiece = 8 << 20; // ---- reading ahead ------------------------------------------------------------------------------ // // One thread (pump) reads whole loads in the order of the plan, each into a buffer of its // own. The main thread takes a load's tensors in order as each is complete, so the copies // to the device still overlap the reads behind them. What the two threads share is in this // struct and is touched under `mu` only; a buffer's bytes are written by the pump's reads // and read by the main thread only for tensors whose reads are over. struct StoreIo::Ahead { struct Item { const TrunkEntry* e = nullptr; int64_t at = 0, len = 0; // place in the buffer, aligned length int pieces = 0; // reads this tensor takes int left = 0; // of them, not finished yet }; struct Job { enum State { Queued, Reading, Done }; int key = -1; std::vector names; std::vector items; int64_t total = 0; int buf = -1; // its buffer in the pool, from the moment the pump takes it up State state = Queued; // Reading from the moment the pump takes it up until its last read is over bool ready = false; // the buffer is in place: tensors whose reads are over may be taken bool dropped = false; // not wanted any more: goes away as soon as nothing reads or uses it bool in_use = false; // the main thread is taking tensors from it std::string error; }; IoEngine* io = nullptr; int file = -1; int64_t fsize = 0; int depth = 0; std::mutex mu; std::condition_variable cv; bool stop = false; std::vector> plan; // in the order the loads will be asked for std::vector> leaving; // dropped while still being read or used std::vector pool; // depth + 1 buffers, each grows to the largest load it held std::vector free_bufs; // Set before the thread starts: the buffers were made at full size and page-locked by // `pin_bk` (copies made ahead read from them), so they must not grow. bool fixed = false; Backend* pin_bk = nullptr; std::thread thread; // mu held. A dropped job that nothing reads or uses gives its buffer back and is deleted. void settle(Job* j) { if (!j->dropped || j->in_use || j->state == Job::Reading) return; if (j->buf >= 0) free_bufs.push_back(j->buf); for (auto* list : {&plan, &leaving}) for (size_t i = 0; i < list->size(); ++i) if ((*list)[i].get() == j) { list->erase(list->begin() + (std::ptrdiff_t)i); return; } } // mu held. Marks a job of the plan as not wanted and moves it out of the plan. void drop(std::unique_ptr j) { j->dropped = true; Job* p = j.get(); leaving.push_back(std::move(j)); settle(p); } }; bool trunk_read_as_f32(const std::string& name) { static const std::string tail = "kv_b_proj.weight"; return name.size() >= tail.size() && name.compare(name.size() - tail.size(), tail.size(), tail) == 0; } WeightDesc trunk_weight_desc(const TrunkEntry& e) { WeightDesc d; d.as_f32 = trunk_read_as_f32(e.name); if (e.dtype == "BF16") d.fmt = WFmt::BF16; else if (e.dtype == "F32") d.fmt = WFmt::F32; else if (e.dtype == "F16") d.fmt = WFmt::F16; else HK_FAIL("tensor %s has dtype %s, which the engine cannot load", e.name.c_str(), e.dtype.c_str()); if (e.shape.size() <= 1) { d.rows = 1; d.cols = (int)e.numel(); } else { d.rows = e.rows(); d.cols = e.cols(); } return d; } void decode_to_f32(const std::string& dtype, const uint8_t* src, int64_t n, float* dst) { if (dtype == "F32") { memcpy(dst, src, (size_t)n * 4); } else if (dtype == "BF16") { for (int64_t i = 0; i < n; ++i) dst[i] = bf16_to_f32(load_le16(src + 2 * i)); } else if (dtype == "F16") { for (int64_t i = 0; i < n; ++i) dst[i] = f16_to_f32(load_le16(src + 2 * i)); } else { HK_FAIL("cannot decode dtype %s to float", dtype.c_str()); } } StoreIo::StoreIo(const Store& store, IoEngine& io) : store_(&store), io_(&io) { trunk_file_ = io.open(store.trunk_path()); expert_files_.assign((size_t)store.config().layers, -1); } StoreIo::~StoreIo() { // a load that was copied ahead and never asked for goes back first: it holds a buffer try { drop_pre(); } catch (...) { } if (ahead_) { { std::lock_guard lk(ahead_->mu); ahead_->stop = true; } ahead_->cv.notify_all(); if (ahead_->thread.joinable()) ahead_->thread.join(); // the load it was reading is finished first: nothing writes after this if (ahead_->fixed) for (AlignedBuf& b : ahead_->pool) ahead_->pin_bk->unpin(b.data()); } if (stage_pinned_) copy_bk_->unpin(stage_buf_.data()); } void StoreIo::enable_read_ahead(IoEngine* io, int depth, Backend* copy_bk, int64_t buf_bytes) { HK_CHECK(!ahead_, "internal: reading ahead was already set up"); // loads kept in RAM can be copied ahead whether or not anything is read ahead if (copy_bk && copy_bk->can_load_async()) copy_bk_ = copy_bk; if (!io || depth <= 0) return; std::unique_ptr a(new Ahead()); a->io = io; a->depth = depth; a->file = io->open(store_->trunk_path()); a->fsize = io->file_size(a->file); a->pool.resize((size_t)depth + 1); for (int i = depth; i >= 0; --i) a->free_bufs.push_back(i); if (copy_bk_ && buf_bytes > 0) { // A copy started ahead reads its buffer after the call that started it has returned. // That takes page-locked memory, and a locked buffer cannot grow: so all of them now, at // the size of the largest load. If the memory is not there or the system does not lock // it, the buffers grow as needed and only loads kept in RAM are copied ahead. size_t locked = 0; bool ok = true; try { for (AlignedBuf& b : a->pool) b.resize(align_up(buf_bytes)); } catch (const std::exception&) { ok = false; } for (; ok && locked < a->pool.size(); ++locked) if (!copy_bk_->pin(a->pool[locked].data(), a->pool[locked].size())) break; if (ok && locked == a->pool.size()) { a->fixed = true; a->pin_bk = copy_bk_; } else { for (size_t i = 0; i < locked; ++i) copy_bk_->unpin(a->pool[i].data()); for (AlignedBuf& b : a->pool) b.reset(); } } ahead_ = std::move(a); ahead_->thread = std::thread([this] { pump(); }); } int StoreIo::ahead_depth() const { return ahead_ ? ahead_->depth : 0; } void StoreIo::plan_ahead(const std::vector& upcoming) { if (!ahead_) return; Ahead& a = *ahead_; // new jobs are laid out before the lock is taken: only this thread ever asks the store std::vector> fresh(upcoming.size()); for (size_t u = 0; u < upcoming.size() && (int)u <= a.depth; ++u) { std::unique_ptr j(new Ahead::Job()); j->key = upcoming[u].key; j->names = upcoming[u].names; j->items.resize(j->names.size()); for (size_t i = 0; i < j->names.size(); ++i) { Ahead::Item& it = j->items[i]; it.e = &store_->get(j->names[i]); HK_CHECK(it.e->offset % kIoAlign == 0, "%s does not start on a 4 KB boundary in trunk.bin", it.e->name.c_str()); it.at = j->total; it.len = align_up(it.e->nbytes); for (int64_t pos = 0; pos < it.len; pos += kTrunkPiece) if (it.e->offset + pos < a.fsize) ++it.pieces; // what lies past the end of the file is padding, not read it.left = it.pieces; j->total += it.len; } fresh[u] = std::move(j); } { std::lock_guard lk(a.mu); std::vector> next; for (size_t u = 0; u < fresh.size(); ++u) { if (!fresh[u]) continue; std::unique_ptr have; for (auto& o : a.plan) if (o && o->key == fresh[u]->key && o->names == fresh[u]->names && o->error.empty()) { have = std::move(o); break; } next.push_back(have ? std::move(have) : std::move(fresh[u])); } for (auto& o : a.plan) if (o) a.drop(std::move(o)); a.plan = std::move(next); } a.cv.notify_all(); } // the thread that reads ahead void StoreIo::pump() { Ahead& a = *ahead_; typedef Ahead::Job Job; std::unique_lock lk(a.mu); for (;;) { Job* job = nullptr; a.cv.wait(lk, [&] { if (a.stop) return true; job = nullptr; for (auto& j : a.plan) if (j->state == Job::Queued) { job = j.get(); break; } if (!job) return false; if (!a.free_bufs.empty()) return true; // No buffer left. A load further down the plan that was read earlier gives way: the one // asked for first must never wait for one asked for later. for (size_t i = a.plan.size(); i-- > 0;) { Job* o = a.plan[i].get(); if (o == job) break; if (o->state == Job::Done && !o->in_use && o->buf >= 0) { a.free_bufs.push_back(o->buf); o->buf = -1; o->state = Job::Queued; o->ready = false; for (Ahead::Item& it : o->items) it.left = it.pieces; return true; } } return false; }); if (a.stop) return; const int b = a.free_bufs.back(); a.free_bufs.pop_back(); job->buf = b; job->state = Job::Reading; // from here on the job stays alive until this thread says Done lk.unlock(); // nobody else touches this job's buffer until it is marked ready std::string error; int pending = 0; uint8_t* base = nullptr; try { // a page-locked buffer has its size for good: a load that does not fit is read the // ordinary way by whoever asks for it if (a.fixed && job->total > a.pool[(size_t)b].size()) throw Error("larger than the buffers of reading ahead"); a.pool[(size_t)b].reserve(job->total); base = a.pool[(size_t)b].data(); for (size_t i = 0; i < job->items.size(); ++i) { const Ahead::Item& it = job->items[i]; for (int64_t pos = 0; pos < it.len; pos += kTrunkPiece) if (it.e->offset + pos >= a.fsize) memset(base + it.at + pos, 0, (size_t)std::min(kTrunkPiece, it.len - pos)); } } catch (const std::exception& e) { error = e.what(); } lk.lock(); job->ready = true; if (!error.empty()) job->error = error; lk.unlock(); a.cv.notify_all(); if (error.empty()) { try { for (size_t i = 0; i < job->items.size(); ++i) { const Ahead::Item& it = job->items[i]; for (int64_t pos = 0; pos < it.len; pos += kTrunkPiece) { if (it.e->offset + pos >= a.fsize) continue; IoRequest r; r.file = a.file; r.offset = it.e->offset + pos; r.len = std::min(kTrunkPiece, it.len - pos); r.dst = base + it.at + pos; r.tag = ((uint64_t)i << 40) | (uint64_t)pos; a.io->submit(r); ++pending; } } } catch (const std::exception& e) { error = e.what(); } } IoCompletion c[16]; while (pending > 0) { int n = 0; try { n = a.io->wait(c, 16, 1); } catch (const std::exception& e) { if (error.empty()) error = e.what(); } if (n <= 0) { if (error.empty()) error = "trunk reads stalled while reading ahead"; break; // the engine says nothing is in flight any more } lk.lock(); for (int k = 0; k < n; ++k) { const size_t i = (size_t)(c[k].tag >> 40); const int64_t pos = (int64_t)(c[k].tag & (((uint64_t)1 << 40) - 1)); Ahead::Item& it = job->items[i]; const int64_t want = std::min(kTrunkPiece, it.len - pos); if (c[k].error != 0) { if (error.empty()) error = strfmt("reading %s failed: %s", it.e->name.c_str(), io_error_text(c[k].error).c_str()); } else if (c[k].bytes < want) { // only legal when the file ends inside this piece: the rest is padding if (it.e->offset + pos + c[k].bytes >= a.fsize) memset(base + it.at + pos + c[k].bytes, 0, (size_t)(want - c[k].bytes)); else if (error.empty()) error = strfmt("short read in %s (%lld of %lld bytes)", it.e->name.c_str(), (long long)c[k].bytes, (long long)want); } --it.left; } pending -= n; if (!error.empty()) job->error = error; // whoever waits for a tensor of this load sees it lk.unlock(); a.cv.notify_all(); } // Every read is over (the loop above goes on after an error until they all are). Done and // the clean-up are one step: a job dropped meanwhile is deleted here. lk.lock(); if (!error.empty()) job->error = error; job->state = Job::Done; a.settle(job); a.cv.notify_all(); } } // The announced load with this key and these names, marked as in use (its buffer stays // until ahead_release). Null: there is none, or it failed. void* StoreIo::ahead_find(const std::vector& names, int key) { Ahead& a = *ahead_; std::lock_guard lk(a.mu); for (auto& j : a.plan) if (j->key == key && j->names == names && j->error.empty()) { j->in_use = true; return j.get(); } return nullptr; } // done with a load taken by ahead_find: it leaves the plan and its buffer is free again void StoreIo::ahead_release(void* p) { Ahead& a = *ahead_; Ahead::Job* job = (Ahead::Job*)p; { std::lock_guard lk(a.mu); job->in_use = false; if (!job->dropped) { for (auto& j : a.plan) if (j.get() == job) { a.drop(std::move(j)); break; } for (size_t i = 0; i < a.plan.size(); ++i) if (!a.plan[i]) { a.plan.erase(a.plan.begin() + (std::ptrdiff_t)i); break; } } else { a.settle(job); } } a.cv.notify_all(); } bool StoreIo::load_ahead(Backend& bk, const std::vector& names, int key, std::vector& out, Kept* keep) { Ahead& a = *ahead_; typedef Ahead::Job Job; Job* job = (Job*)ahead_find(names, key); if (!job) return false; auto release = [&]() { ahead_release(job); }; try { for (size_t next = 0; next < names.size(); ++next) { const uint8_t* base = nullptr; { std::unique_lock lk(a.mu); const double t_wait = now_sec(); a.cv.wait(lk, [&] { return !job->error.empty() || (job->ready && job->items[next].left == 0); }); trunk_wait_seconds_ += now_sec() - t_wait; if (!job->error.empty()) throw Error(job->error); base = a.pool[(size_t)job->buf].data(); } // all of this tensor is in memory: to the device, while the reads behind it go on const Ahead::Item& it = job->items[next]; WeightData data; data.dense = base + it.at; const double t_copy = now_sec(); out[next] = bk.load(trunk_weight_desc(*it.e), data); trunk_copy_seconds_ += now_sec() - t_copy; bytes_read_ += it.e->nbytes; } if (keep) { // every read of this load is over and its buffer is ours until release(): the bytes are stable std::vector at(names.size()); for (size_t i = 0; i < names.size(); ++i) at[i] = job->items[i].at; const uint8_t* base = nullptr; { std::lock_guard lk(a.mu); base = a.pool[(size_t)job->buf].data(); } capture(*keep, names, at, base, job->total); } } catch (...) { for (Weight*& w : out) { if (w) bk.unload(w); w = nullptr; } release(); throw; } release(); return true; } // ---- loads kept in RAM -------------------------------------------------------------------------- void StoreIo::keep_in_ram(const std::vector& keys) { std::unordered_map next; for (int key : keys) { if (key < 0) continue; auto it = kept_.find(key); if (it != kept_.end()) next[key] = std::move(it->second); // what was read already stays else next[key] = Kept(); } kept_ = std::move(next); ram_held_ = 0; for (const auto& kv : kept_) if (kv.second.full) ram_held_ += kv.second.buf.size(); keep_failed_ = false; } bool StoreIo::in_ram(int key) const { auto it = kept_.find(key); return it != kept_.end() && it->second.full; } std::vector StoreIo::load_kept(Backend& bk, const Kept& k) { std::vector out(k.names.size(), nullptr); try { for (size_t i = 0; i < k.names.size(); ++i) { const TrunkEntry& e = store_->get(k.names[i]); WeightData data; data.dense = k.buf.data() + k.at[i]; const double t_copy = now_sec(); out[i] = bk.load(trunk_weight_desc(e), data); trunk_copy_seconds_ += now_sec() - t_copy; bytes_from_ram_ += e.nbytes; } } catch (...) { for (Weight* w : out) if (w) bk.unload(w); throw; } return out; } void StoreIo::capture(Kept& k, const std::vector& names, const std::vector& at, const uint8_t* base, int64_t total) { if (keep_failed_ || total <= 0) return; try { k.buf.resize(total); } catch (const std::exception& e) { // out of RAM for it: this load and the ones not read yet stay on the disk HK_WARN("no RAM left to keep more of the trunk (%s held): %s", human_bytes((double)ram_held_).c_str(), e.what()); keep_failed_ = true; return; } // a few GB at the speed of memory: in slices, on every core const int64_t slice = (int64_t)8 << 20; uint8_t* dst = k.buf.data(); parallel_for((total + slice - 1) / slice, 1, [&](int64_t a, int64_t b) { for (int64_t s = a; s < b; ++s) memcpy(dst + s * slice, base + s * slice, (size_t)std::min(slice, total - s * slice)); }); k.names = names; k.at = at; k.full = true; ram_held_ += k.buf.size(); } // ---- copying ahead ------------------------------------------------------------------------------- // what the card must have left after a load was copied ahead, for the work that goes on meanwhile static const int64_t kCopyAheadSpare = (int64_t)1 << 30; // Puts a load kept in RAM into the page-locked staging buffer, where a copy ahead may // read it. False: there is no such buffer (no memory, or the system does not lock it). bool StoreIo::stage(Backend& bk, const Kept& k) { if (stage_refused_) return false; const int64_t total = k.buf.size(); if (stage_buf_.size() < total) { // nothing reads the buffer now: a copy ahead is over before the next one is staged if (stage_pinned_) bk.unpin(stage_buf_.data()); stage_pinned_ = false; try { stage_buf_.resize(total); } catch (const std::exception&) { stage_buf_.reset(); stage_refused_ = true; return false; } if (!bk.pin(stage_buf_.data(), stage_buf_.size())) { stage_buf_.reset(); stage_refused_ = true; return false; } stage_pinned_ = true; } const int64_t slice = (int64_t)8 << 20; uint8_t* dst = stage_buf_.data(); const uint8_t* src = k.buf.data(); parallel_for((total + slice - 1) / slice, 1, [&](int64_t a, int64_t b) { for (int64_t s = a; s < b; ++s) memcpy(dst + s * slice, src + s * slice, (size_t)std::min(slice, total - s * slice)); }); return true; } void StoreIo::prefetch(Backend& bk, const std::vector& names, int key) { if (!copy_bk_ || copy_off_ || &bk != copy_bk_ || key < 0 || names.empty()) return; if (pre_.active && (pre_.key != key || pre_.names != names)) drop_pre(); try { if (!pre_.active) { if (pre_skip_ == key) return; auto kept = kept_.find(key); const bool in_ram = kept != kept_.end() && kept->second.full; if (in_ram) { if (kept->second.names != names) return; // load_trunk_many deals with that } else if (!ahead_ || !ahead_->fixed) { return; } // room on the card for this load next to the one in use, or it waits for its turn int64_t total = 0; for (const std::string& n : names) total += store_->get(n).nbytes; if (bk.mem_free() < total + kCopyAheadSpare || (in_ram && !stage(bk, kept->second))) { pre_skip_ = key; // not asked again for this load return; } void* job = nullptr; if (!in_ram) { job = ahead_find(names, key); if (!job) { pre_skip_ = key; // not announced (the plan only changes when a layer begins), or its reads failed return; } } pre_ = Pre(); pre_.active = true; pre_.key = key; pre_.names = names; pre_.w.assign(names.size(), nullptr); pre_.job = job; pre_.staged = in_ram; if (in_ram) { // all of it is in memory: every tensor starts for the card now const Kept& k = kept->second; for (; pre_.n < names.size(); ++pre_.n) { const TrunkEntry& e = store_->get(names[pre_.n]); WeightData data; data.dense = stage_buf_.data() + k.at[pre_.n]; pre_.w[pre_.n] = bk.load_async(trunk_weight_desc(e), data); bytes_ahead_ += e.nbytes; } return; } } if (pre_.staged) return; // the tensors the reading thread has finished since the last call, in order Ahead& a = *ahead_; Ahead::Job* job = (Ahead::Job*)pre_.job; while (pre_.n < names.size()) { const uint8_t* base = nullptr; { std::lock_guard lk(a.mu); if (!job->error.empty() || !job->ready || job->items[pre_.n].left != 0) break; base = a.pool[(size_t)job->buf].data(); } const Ahead::Item& it = job->items[pre_.n]; WeightData data; data.dense = base + it.at; pre_.w[pre_.n] = bk.load_async(trunk_weight_desc(*it.e), data); ++pre_.n; bytes_read_ += it.e->nbytes; bytes_ahead_ += it.e->nbytes; } } catch (const std::exception& e) { // The card had no room after all. What was handed over goes back, and from here on // every load is copied when its turn comes. HK_INFO("copying the trunk ahead is given up (%s): each layer's trunk is copied when its turn comes", e.what()); copy_off_ = true; drop_pre(); } } // the load that was copied ahead is the one asked for: the rest of it, then wait for the copies std::vector StoreIo::finish_pre(Backend& bk, Kept* keep) { try { if (pre_.staged) { for (const std::string& n : pre_.names) bytes_from_ram_ += store_->get(n).nbytes; } else { Ahead& a = *ahead_; Ahead::Job* job = (Ahead::Job*)pre_.job; while (pre_.n < pre_.names.size()) { const uint8_t* base = nullptr; { std::unique_lock lk(a.mu); const double t_wait = now_sec(); a.cv.wait(lk, [&] { return !job->error.empty() || (job->ready && job->items[pre_.n].left == 0); }); trunk_wait_seconds_ += now_sec() - t_wait; if (!job->error.empty()) throw Error(job->error); base = a.pool[(size_t)job->buf].data(); } const Ahead::Item& it = job->items[pre_.n]; WeightData data; data.dense = base + it.at; const double t_copy = now_sec(); pre_.w[pre_.n] = bk.load_async(trunk_weight_desc(*it.e), data); trunk_copy_seconds_ += now_sec() - t_copy; ++pre_.n; bytes_read_ += it.e->nbytes; } } const double t_copy = now_sec(); bk.wait_loads(); trunk_copy_seconds_ += now_sec() - t_copy; if (keep && !pre_.staged) { // every read of this load is over, every copy from its buffer too: the bytes are stable Ahead& a = *ahead_; Ahead::Job* job = (Ahead::Job*)pre_.job; std::vector at(pre_.names.size()); for (size_t i = 0; i < at.size(); ++i) at[i] = job->items[i].at; const uint8_t* base = nullptr; { std::lock_guard lk(a.mu); base = a.pool[(size_t)job->buf].data(); } capture(*keep, pre_.names, at, base, job->total); } } catch (...) { drop_pre(); throw; } std::vector out = std::move(pre_.w); void* job = pre_.job; pre_ = Pre(); if (job) ahead_release(job); return out; } // gives back a load that was copied ahead and is not wanted (or failed) void StoreIo::drop_pre() { if (!pre_.active) return; std::vector w = std::move(pre_.w); void* job = pre_.job; pre_ = Pre(); // unload waits for a copy that is still on its way, so the buffer the copies read from // is released after it std::exception_ptr err; for (Weight* x : w) { if (!x) continue; try { copy_bk_->unload(x); } catch (...) { if (!err) err = std::current_exception(); } } try { copy_bk_->wait_loads(); } catch (...) { if (!err) err = std::current_exception(); } if (job) ahead_release(job); if (err) std::rethrow_exception(err); } void StoreIo::read_trunk(const TrunkEntry& e, std::vector& out) { out.resize((size_t)e.nbytes); io_->read_range(trunk_file_, e.offset, e.nbytes, out.data()); bytes_read_ += e.nbytes; } Weight* StoreIo::load_trunk(Backend& bk, const std::string& name) { const TrunkEntry& e = store_->get(name); WeightDesc d = trunk_weight_desc(e); // trunk tensors start on a 4 KB boundary in trunk.bin: the aligned read needs no bounce copy AlignedBuf buf(align_up(e.nbytes)); io_->read_aligned(trunk_file_, e.offset, align_up(e.nbytes), buf.data()); bytes_read_ += e.nbytes; WeightData data; data.dense = buf.data(); return bk.load(d, data); } std::vector StoreIo::load_trunk_many(Backend& bk, const std::vector& names, int key) { Kept* entry = nullptr; // this load is one to keep in RAM if (key >= 0 && !names.empty()) { auto it = kept_.find(key); if (it != kept_.end()) entry = &it->second; } pre_skip_ = -1; if (pre_.active) { // a load was copied ahead: if it is this one it is taken, anything else goes back const bool same = pre_.key == key && pre_.names == names; const bool in_ram = entry && entry->full && entry->names == names; if (same && pre_.staged == in_ram) return finish_pre(bk, entry && !entry->full ? entry : nullptr); drop_pre(); } if (entry && entry->full) { if (entry->names == names) return load_kept(bk, *entry); // other tensors under this key than last time: what is held is of no use any more ram_held_ -= entry->buf.size(); entry->buf.reset(); entry->full = false; } if (ahead_ && key >= 0 && !names.empty()) { std::vector got(names.size(), nullptr); if (load_ahead(bk, names, key, got, entry)) return got; } const int64_t kPiece = kTrunkPiece; struct Item { const TrunkEntry* e = nullptr; int64_t at = 0, len = 0; // place in the buffer, aligned length int left = 0; // pieces still being read }; std::vector items(names.size()); int64_t total = 0; for (size_t i = 0; i < names.size(); ++i) { items[i].e = &store_->get(names[i]); items[i].at = total; items[i].len = align_up(items[i].e->nbytes); total += items[i].len; } std::vector out(names.size(), nullptr); if (names.empty()) return out; HK_CHECK(io_->in_flight() == 0, "load_trunk_many called while other reads are in flight"); AlignedBuf once; const bool keep = bk.is_gpu() || total <= kTrunkKeepBytes; if (keep) many_buf_.reserve(total); else once.resize(total); uint8_t* base = keep ? many_buf_.data() : once.data(); const int64_t fsize = io_->file_size(trunk_file_); for (size_t i = 0; i < items.size(); ++i) { Item& it = items[i]; HK_CHECK(it.e->offset % kIoAlign == 0, "%s does not start on a 4 KB boundary in trunk.bin", it.e->name.c_str()); for (int64_t pos = 0; pos < it.len; pos += kPiece) { IoRequest r; r.file = trunk_file_; r.offset = it.e->offset + pos; r.len = std::min(kPiece, it.len - pos); r.dst = base + it.at + pos; r.tag = ((uint64_t)i << 40) | (uint64_t)pos; if (r.offset >= fsize) { // the padding after the last tensor of the file memset(r.dst, 0, (size_t)r.len); continue; } io_->submit(r); ++it.left; } } IoCompletion c[16]; std::string error; auto take = [&](int n) { for (int k = 0; k < n; ++k) { const size_t i = (size_t)(c[k].tag >> 40); const int64_t pos = (int64_t)(c[k].tag & (((uint64_t)1 << 40) - 1)); Item& it = items[i]; --it.left; const int64_t want = std::min(kPiece, it.len - pos); if (c[k].error != 0) { if (error.empty()) error = strfmt("reading %s failed: %s", it.e->name.c_str(), io_error_text(c[k].error).c_str()); } else if (c[k].bytes < want) { // only legal when the file ends inside this piece: the rest is padding if (it.e->offset + pos + c[k].bytes >= fsize) memset(base + it.at + pos + c[k].bytes, 0, (size_t)(want - c[k].bytes)); else if (error.empty()) error = strfmt("short read in %s (%lld of %lld bytes)", it.e->name.c_str(), (long long)c[k].bytes, (long long)want); } } }; size_t next = 0; try { while (next < items.size()) { if (!error.empty()) throw Error(error); Item& it = items[next]; if (it.left > 0) { const double t_wait = now_sec(); const int n = io_->wait(c, 16, 1); trunk_wait_seconds_ += now_sec() - t_wait; HK_CHECK(n > 0, "trunk reads stalled at %s", it.e->name.c_str()); take(n); continue; } // all of this tensor is in memory: to the device, while the reads behind it go on WeightData data; data.dense = base + it.at; const double t_copy = now_sec(); out[next] = bk.load(trunk_weight_desc(*it.e), data); trunk_copy_seconds_ += now_sec() - t_copy; bytes_read_ += it.e->nbytes; ++next; take(io_->wait(c, 16, 0)); // collect what finished meanwhile, and keep the queue fed } if (entry) { std::vector at(items.size()); for (size_t i = 0; i < items.size(); ++i) at[i] = items[i].at; capture(*entry, names, at, base, total); } } catch (...) { // nothing may still be writing into the buffer when this returns, and nothing stays loaded while (io_->in_flight() > 0) io_->wait(c, 16, 1); for (Weight* w : out) if (w) bk.unload(w); throw; } return out; } void StoreIo::read_trunk_rows_f32(const TrunkEntry& e, int row0, int n, float* out) { const int cols = e.cols(); const int es = dtype_size(e.dtype); HK_CHECK(es > 0 && row0 >= 0 && row0 + n <= e.rows(), "row range [%d, +%d) is outside %s", row0, n, e.name.c_str()); std::vector raw((size_t)n * (size_t)cols * (size_t)es); io_->read_range(trunk_file_, e.offset + (int64_t)row0 * cols * es, (int64_t)raw.size(), raw.data()); bytes_read_ += (int64_t)raw.size(); decode_to_f32(e.dtype, raw.data(), (int64_t)n * cols, out); } const uint8_t* StoreIo::read_trunk_rows_raw(const TrunkEntry& e, int row0, int n, AlignedBuf& buf) { const int64_t es = dtype_size(e.dtype), cols = e.cols(); HK_CHECK(es > 0 && row0 >= 0 && n >= 0 && row0 + n <= e.rows(), "row range [%d, +%d) is outside %s", row0, n, e.name.c_str()); const int64_t off = e.offset + (int64_t)row0 * cols * es, len = (int64_t)n * cols * es; // the 4 KB aligned range around the rows, read in place: no second copy, many pieces in flight const int64_t a0 = align_down(off), a1 = align_up(off + len); buf.reserve(a1 - a0); if (a1 > a0) io_->read_aligned(trunk_file_, a0, a1 - a0, buf.data()); bytes_read_ += len; return buf.data() + (off - a0); } void StoreIo::embed(const int32_t* ids, int n, float* out) { const TrunkEntry& e = store_->get(store_->config().n_embed()); const int d = e.cols(); for (int i = 0; i < n; ++i) { HK_CHECK(ids[i] >= 0 && ids[i] < e.rows(), "token id %d is outside the vocabulary (%d)", ids[i], e.rows()); read_trunk_rows_f32(e, ids[i], 1, out + (size_t)i * (size_t)d); } } int StoreIo::expert_file(int layer) { int& f = expert_files_.at((size_t)layer); if (f < 0) { const ExpertLayer& el = store_->experts(layer); f = io_->open(store_->path(el.file)); AlignedBuf hdr(kHkxHeaderBytes); io_->read_aligned(f, 0, kHkxHeaderBytes, hdr.data()); hkx_check_header(el, hdr.data()); HK_CHECK(io_->file_size(f) >= el.record_offset(el.n_experts), "%s is shorter than its header says (interrupted conversion?)", el.file.c_str()); } return f; } } // namespace hk