// Setup shared by run and chat: store, backend, I/O, reader. #pragma once #include #include "cli/args.h" #include "cli/commands.h" #include "format/store.h" #include "gpu/backend.h" #include "io/file_io.h" #include "reader/reader.h" namespace hk { #define HK_ENGINE_OPTIONS \ "backend", "engine", "buffered", "chunk", "head-chunk", "topk", "io-depth", "read-ahead", "ahead-threads", "trunk-ram", \ "expert-block", "pin", "copy-ahead" struct Engine { Store store; std::unique_ptr bk; std::unique_ptr reader_io, ahead_io; // before the reader: it uses them until it is gone std::unique_ptr reader; bool keep_head = false; // set before open(): the reader keeps its output head on the device (draft and check) int64_t trunk_ram = 0; // bytes of trunk the reader will keep in RAM once it has read them void open(const Args& a) { store = Store::open(a.need_pos(0, "the store directory")); bk = Backend::create(a.str("backend", "auto")); IoOptions io_opt; io_opt.engine = a.str("engine", "auto"); io_opt.direct = !a.flag("buffered"); io_opt.queue_depth = (int)a.num("io-depth", 16) * 2; // the thread-pool reader (where io_uring is blocked) has one read in flight per thread io_opt.threads = std::max(io_opt.threads, (int)a.num("io-depth", 16)); reader_io = IoEngine::create(io_opt); ReaderOptions ro; ro.chunk = (int)a.num("chunk", ro.chunk); ro.head_chunk = (int)a.num("head-chunk", ro.head_chunk); ro.topk = (int)a.num("topk", ro.topk); ro.io_depth = (int)a.num("io-depth", ro.io_depth); ro.keep_head = keep_head; ro.expert_block = a.num("expert-block", 1) != 0; // 0: an expert goes to the card in fifteen pieces ro.pin = a.num("pin", 1) != 0; // 0: read buffers are not page-locked ro.copy_ahead = a.num("copy-ahead", 1) != 0; // 0: a layer's trunk is copied to the card when its turn comes reader.reset(new Reader(store, *bk, *reader_io, ro)); // the next layers' trunk is read while the device computes (--read-ahead 0: off) const int ahead = (int)a.num("read-ahead", 2); HK_CHECK(ahead >= 0 && ahead <= 8, "--read-ahead is the number of layers read ahead, 0 to 8"); if (ahead > 0) { IoOptions ao = io_opt; ao.threads = std::max(1, (int)a.num("ahead-threads", 8)); ao.queue_depth = std::max(2, ao.threads); ahead_io = IoEngine::create(ao); } reader->read_ahead(ahead_io.get(), ahead); // with 0 too: copying ahead is set up there if (reader->copies_ahead()) HK_INFO("each layer's trunk is copied to the card while the layer before it reads its experts (--copy-ahead 0: when its turn comes)"); // part of the trunk stays in RAM between sweeps (--trunk-ram GB, 0 = none, default: what is free) trunk_ram = reader->keep_trunk(trunk_ram_budget(a, true)); if (trunk_ram > 0) HK_INFO("%s of the trunk will stay in RAM once read, so that later sweeps read less (--trunk-ram 0: none)", human_bytes((double)trunk_ram).c_str()); } }; } // namespace hk