Download src/reader/reader.h from Ozomozyan/hkimi: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/Ozomozyan/hkimi/resolve/main/src/reader/reader.h
- Command line
-
hf download hf://Ozomozyan/hkimi/src/reader/reader.h
-
curl -L -o reader.h https://huggingface.co/Ozomozyan/hkimi/resolve/main/src/reader/reader.h
10.5 kB
| // The reader: "real Kimi". It runs the unmodified model (native MXFP4 experts, | |
| // trunk at shipped precision) over whole sequences, one layer at a time: | |
| // | |
| // for each layer: | |
| // read this layer's trunk weights from the SSD, run attention for every | |
| // position, route every position, then read each needed expert once and | |
| // apply it to all the positions that picked it | |
| // | |
| // So a sweep costs one pass over the model on disk however many positions it | |
| // covers, which is why checking several drafted tokens costs about as much as | |
| // writing one. | |
| // | |
| // Sequences are resumable. A SeqCheckpoint holds what the model needs to go on | |
| // after `pos` tokens: the KDA state of every KDA layer and the latent key/value | |
| // cache of every full-attention layer. | |
| namespace hk { | |
| struct ReaderOptions { | |
| int chunk = 256; // positions pushed through the device at once | |
| int head_chunk = 32; // positions per lm_head pass (logits are vocab-wide) | |
| int topk = 16; // real Kimi's best tokens kept per position | |
| int io_depth = 16; // expert reads in flight | |
| // The output head (final norms and lm_head, 2.35 GB on K3.1) stays on the device between | |
| // sweeps. The drafter borrows the same matrix. | |
| bool keep_head = false; | |
| // How an expert record gets to a GPU: as one block (one allocation and one copy for the | |
| // 17.5 MB record instead of fifteen), and from page-locked buffers (the copy goes straight | |
| // from the buffer the disk read into). Only how the same bytes travel changes. | |
| bool expert_block = true; | |
| bool pin = true; | |
| // On a GPU the next layer's trunk starts for the card while this layer's experts are read | |
| // and applied (StoreIo::prefetch). Only when the bytes travel changes. Needs `pin`. | |
| bool copy_ahead = true; | |
| bool keep_logits = false; // tests: return full logits rows | |
| // Layer tests (`hkimi layer-test`): run only layers [first_layer, last_layer] on hidden | |
| // states the job brings itself, and hand hidden states back instead of logits. | |
| int first_layer = 0; | |
| int last_layer = -1; // -1: the model's last layer | |
| bool hidden_io = false; // SeqJob::hidden_in replaces the embedding lookup; the head is skipped | |
| }; | |
| struct SeqCheckpoint { | |
| int pos = 0; | |
| std::vector<std::vector<float>> kda_S; // per layer (empty for non-KDA layers): H*D x D | |
| std::vector<std::vector<float>> kda_ring; // per layer: 3 x (K-1) x H*D | |
| std::vector<std::vector<float>> mla_C, mla_R, mla_keys; // per layer: pos x dim | |
| // A checkpoint left by a sweep with SeqJob::keep_tail can be moved back. Its KDA states are | |
| // those before the last `tail` positions, and kda_tail holds what it takes to carry them | |
| // over these positions again (the next sweep does that before its own positions). Moving | |
| // the checkpoint back is then only forgetting the end of the tail and of the caches. | |
| int tail = 0; | |
| std::vector<KdaTail> kda_tail; // per layer (empty for non-KDA layers) | |
| void rewind(int new_pos); // pos - tail <= new_pos <= pos | |
| void reset(const ModelConfig& c); // empty state at position 0 | |
| int64_t bytes() const; | |
| int dim_hd = 0, dim_h = 0, dim_c = 0, dim_r = 0, dim_keys = 0; // row widths, set by reset() | |
| }; | |
| // real Kimi's view of one position: its distribution over the next token | |
| struct PosResult { | |
| std::vector<int32_t> top_id; // most likely next tokens, best first | |
| std::vector<float> top_logp; // their log-probabilities | |
| float entropy = 0; // of the full distribution (nats) | |
| int32_t next = -1; // the token that actually follows in the sequence (-1 at the end) | |
| float next_logp = 0; // its log-probability | |
| int next_rank = -1; // 0 = it is real Kimi's top choice | |
| }; | |
| struct SeqJob { | |
| const std::vector<int32_t>* tokens = nullptr; | |
| SeqCheckpoint* ckpt = nullptr; // state before position ckpt->pos (updated if save_at >= 0) | |
| int end = 0; // positions [ckpt->pos, end) are processed | |
| int save_at = -1; // move the checkpoint to this position (between pos and end), -1 = keep it | |
| // Checking drafted tokens: which positions will stand is only known once the sweep is over. | |
| // With keep_tail the checkpoint is moved to `end` (save_at is ignored) and can afterwards be | |
| // put back anywhere down to where this sweep started (SeqCheckpoint::rewind). | |
| bool keep_tail = false; | |
| std::vector<PosResult> out; // one per processed position | |
| std::vector<float> logits; // [n, vocab] when ReaderOptions::keep_logits | |
| // ReaderOptions::hidden_io: hidden states in [n, hidden] (tokens only gives the length), and out | |
| const std::vector<float>* hidden_in = nullptr; | |
| std::vector<float> hidden_out; | |
| }; | |
| // what a sweep holds on the host when a layer is finished, one line per flat row | |
| struct LayerStates { | |
| int rows = 0, d = 0, in_dim = 0, k = 0; | |
| const float* x = nullptr; // the hidden state after the layer [rows, d] | |
| // MoE layers only (null for a dense layer): | |
| const float* res = nullptr; // the hidden state after attention, which the feed-forward output is added to [rows, d] | |
| const float* xlat = nullptr; // input of the routed experts [rows, in_dim] | |
| const float* ylat = nullptr; // their weighted sum [rows, in_dim] | |
| const int32_t* expert = nullptr; // the k experts of each row [rows, k] | |
| const float* weight = nullptr; // and their weights [rows, k] | |
| }; | |
| // Hooks into a sweep. All callbacks run on the sweep thread. | |
| struct SweepObserver { | |
| virtual ~SweepObserver() = default; | |
| // Once per sweep. All positions are numbered as flat rows; row_job[r] is the index (into | |
| // the jobs given to sweep) of the sequence row r belongs to. | |
| virtual void on_sweep_begin(const std::vector<int>& /*row_job*/) {} | |
| virtual void on_layer_begin(int /*layer*/) {} | |
| // the on_linear calls that follow are about positions [a, b) of jobs[job] | |
| virtual void on_chunk(int /*job*/, int /*a*/, int /*b*/) {} | |
| virtual LinHook* lin_hook() { return nullptr; } | |
| // One routed expert, applied to n rows: inputs Xc and outputs Yc, both [n, dim] on the | |
| // host; rows[i] is the flat row of line i. | |
| virtual void on_expert(int /*layer*/, int /*expert*/, const float* /*Xc*/, const float* /*Yc*/, const int32_t* /*rows*/, | |
| int /*n*/, int /*dim*/) {} | |
| // the layer's states, just before on_layer_end | |
| virtual void on_layer_states(int /*layer*/, const LayerStates& /*states*/) {} | |
| virtual void on_layer_end(int /*layer*/) {} | |
| }; | |
| struct SweepStats { | |
| double seconds = 0, io_seconds = 0, expert_seconds = 0, head_seconds = 0; | |
| // a finer split of the same time (`hkimi sweep` prints it) | |
| double attn_seconds = 0; // attention and the dense layers of every chunk, with their copies to and from the device | |
| double expert_wait_seconds = 0; // the part of expert_seconds spent waiting for the disk | |
| double post_seconds = 0; // after the experts: up-projection, shared experts, residual | |
| double free_seconds = 0; // giving a layer's weights back | |
| // Of the time spent loading trunk and head: waiting for the disk with nothing else to do, | |
| // and copying tensors to the device (the reads go on during the copies). | |
| double trunk_wait_seconds = 0, trunk_copy_seconds = 0; | |
| int64_t bytes_read = 0; | |
| int64_t ram_bytes = 0; // trunk bytes that came from RAM and were not read (Reader::keep_trunk) | |
| // Trunk bytes that were on their way to the device before their layer began, and the time | |
| // the layers before spent sending them off (part of their expert_seconds). | |
| int64_t ahead_bytes = 0; | |
| double ahead_seconds = 0; | |
| int positions = 0, expert_reads = 0; | |
| void add(const SweepStats& s) { // totals over several sweeps | |
| seconds += s.seconds; | |
| io_seconds += s.io_seconds; | |
| expert_seconds += s.expert_seconds; | |
| head_seconds += s.head_seconds; | |
| attn_seconds += s.attn_seconds; | |
| expert_wait_seconds += s.expert_wait_seconds; | |
| post_seconds += s.post_seconds; | |
| free_seconds += s.free_seconds; | |
| trunk_wait_seconds += s.trunk_wait_seconds; | |
| trunk_copy_seconds += s.trunk_copy_seconds; | |
| bytes_read += s.bytes_read; | |
| ram_bytes += s.ram_bytes; | |
| ahead_bytes += s.ahead_bytes; | |
| ahead_seconds += s.ahead_seconds; | |
| positions += s.positions; | |
| expert_reads += s.expert_reads; | |
| } | |
| }; | |
| class Reader { | |
| public: | |
| Reader(const Store& store, Backend& bk, IoEngine& io, const ReaderOptions& opt); | |
| ~Reader(); | |
| const ModelConfig& config() const { return store_.config(); } | |
| const Store& store() const { return store_; } | |
| Backend& backend() { return bk_; } | |
| StoreIo& store_io(); | |
| // Reads the trunk of the layers to come while the device works on the current one. `io` is | |
| // a second I/O engine for the reading thread; it must outlive the reader. Call it with | |
| // depth 0 too: copying ahead is set up here. | |
| void read_ahead(IoEngine* io, int depth); | |
| // true when the next layer's trunk will be copied to the device ahead of its turn | |
| bool copies_ahead(); | |
| // Keeps the trunk of some layers in RAM between sweeps, at most `budget` bytes, so a sweep | |
| // reads that much less. The layers are spread evenly over the model, so that the disk has | |
| // work all through a sweep. 0 keeps nothing; a negative budget means what is free now, | |
| // less 16 GB for everything else. Returns the bytes the chosen layers take. | |
| int64_t keep_trunk(int64_t budget); | |
| int64_t trunk_kept_bytes(); // of them, in RAM by now | |
| // lm_head on the device, loaded now if it is not there yet (needs keep_head) | |
| const Weight* lm_head(); | |
| SweepStats sweep(std::vector<SeqJob*>& jobs, SweepObserver* obs = nullptr); | |
| // one sequence | |
| SweepStats sweep(SeqJob& job, SweepObserver* obs = nullptr) { | |
| std::vector<SeqJob*> v{&job}; | |
| return sweep(v, obs); | |
| } | |
| private: | |
| struct Impl; | |
| const Store& store_; | |
| Backend& bk_; | |
| ReaderOptions opt_; | |
| std::unique_ptr<Impl> impl_; | |
| }; | |
| // stats of one logits row | |
| void logits_stats(const float* logits, int vocab, int topk, int32_t next, PosResult& out); | |
| } // namespace hk | |