File size: 29,524 Bytes
68888be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
// hkimi bench-io | inspect | convert | sweep
#include <algorithm>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <set>

#include "cli/args.h"
#include "cli/commands.h"
#include "common/base.h"
#include "common/numeric.h"
#include "convert/convert.h"
#include "format/safetensors.h"
#include "format/store.h"
#include "io/file_io.h"
#include "io/os_info.h"
#include "model/weights.h"
#include "reader/reader.h"

namespace hk {

// bench-io: how fast this disk reads, the way the engine reads it
int cmd_bench_io(const Args& a) {
    a.allow({"size-gb", "block-mb", "depth", "seconds", "engine", "no-random", "buffered", "keep"});
    std::string path = a.need_pos(0, "a file to read, or a directory to create a test file in");
    const int64_t block = a.num("block-mb", 16) * (1 << 20);
    const int depth = (int)a.num("depth", 16);
    const double seconds = a.real("seconds", 10.0);
    namespace fs = std::filesystem;
    bool made = false;
    if (fs::is_directory(fs::u8path(path))) {
        // incompressible data, so that a compressing drive cannot flatter the result
        path = path_join(path, "hkimi-bench.tmp");
        const int64_t size = (int64_t)(a.real("size-gb", 4.0) * 1e9);
        HK_INFO("writing a %s test file to %s ...", human_bytes((double)size).c_str(), path.c_str());
        std::ofstream f(fs::u8path(path), std::ios::binary | std::ios::trunc);
        HK_CHECK(f.good(), "cannot create %s", path.c_str());
        std::vector<uint64_t> buf((size_t)(4 << 20) / 8);
        Rng rng(12345);
        for (int64_t done = 0; done < size; done += (int64_t)buf.size() * 8) {
            for (auto& v : buf) v = rng.next();
            f.write((const char*)buf.data(), (std::streamsize)(buf.size() * 8));
        }
        HK_CHECK(f.good(), "writing the test file failed (disk full?)");
        f.close();
        made = true;
    }
    IoOptions opt;
    opt.engine = a.str("engine", "auto");
    opt.queue_depth = std::max(depth, 1);
    opt.threads = std::max(depth, 1);
    opt.direct = !a.flag("buffered");
    std::unique_ptr<IoEngine> io = IoEngine::create(opt);
    int f = io->open(path);
    const int64_t size = align_down(io->file_size(f), block);
    HK_CHECK(size >= block, "%s is smaller than one %lld MB block", path.c_str(), (long long)(block >> 20));
    const int64_t nblocks = size / block;
    printf("file      : %s (%s)\n", path.c_str(), human_bytes((double)io->file_size(f)).c_str());
    printf("engine    : %s, %s, block %lld MB, depth %d\n", io->name(), io->is_direct(f) ? "direct I/O" : "BUFFERED (not direct)",
           (long long)(block >> 20), depth);
    if (!io->is_direct(f))
        printf("warning   : buffered reads go through the OS cache; the numbers below are not the disk's speed\n");

    std::vector<AlignedBuf> bufs((size_t)depth);
    for (auto& b : bufs) b.resize(block);
    for (int pass = 0; pass < 2; ++pass) {
        const bool random = pass == 1;
        if (random && a.flag("no-random")) break;
        Rng rng(777);
        std::vector<int> free_bufs;
        for (int i = 0; i < depth; ++i) free_bufs.push_back(i);
        int64_t next = 0, bytes = 0;
        int inflight = 0;
        const double t0 = now_sec();
        bool stop = false;
        while (!stop || inflight > 0) {
            while (!stop && !free_bufs.empty()) {
                int b = free_bufs.back();
                free_bufs.pop_back();
                IoRequest r;
                r.file = f;
                r.offset = (random ? (int64_t)rng.below((uint64_t)nblocks) : (next % nblocks)) * block;
                r.len = block;
                r.dst = bufs[(size_t)b].data();
                r.tag = (uint64_t)b;
                io->submit(r);
                ++next;
                ++inflight;
            }
            IoCompletion c[16];
            int n = io->wait(c, 16, 1);
            for (int i = 0; i < n; ++i) {
                HK_CHECK(c[i].error == 0, "read failed: %s", io_error_text(c[i].error).c_str());
                bytes += c[i].bytes;
                free_bufs.push_back((int)c[i].tag);
                --inflight;
            }
            if (now_sec() - t0 >= seconds || (!random && next >= nblocks && seconds <= 0)) stop = true;
        }
        const double dt = now_sec() - t0;
        const double mbs = (double)bytes / 1e6 / dt;
        printf("%-10s: %8.0f MB/s  (%s in %.1f s)\n", random ? "random" : "sequential", mbs, human_bytes((double)bytes).c_str(), dt);
        if (!random) printf("            a full 1.56 TB sweep at this speed: about %.0f s\n", 1.56e12 / (mbs * 1e6));
    }
    if (made && !a.flag("keep")) {
        std::error_code ec;
        fs::remove(fs::u8path(path), ec);
        if (ec) HK_WARN("could not delete %s, remove it by hand", path.c_str());
    }
    return 0;
}

// inspect: does a checkpoint (or a store) look the way the engine expects?
static int inspect_store(const std::string& dir) {
    Store s = Store::open(dir);
    const ModelConfig& c = s.config();
    printf("store     : %s\n", dir.c_str());
    printf("model     : %s\n", c.summary().c_str());
    int64_t tb = 0, eb = 0;
    for (const auto& e : s.trunk()) tb += e.nbytes;
    for (const auto& el : s.expert_layers()) eb += el.record_bytes() * el.n_experts;
    printf("trunk     : %zu tensors, %s\n", s.trunk().size(), human_bytes((double)tb).c_str());
    printf("experts   : %zu of %d MoE layers, %s", s.expert_layers().size(), c.n_moe_layers(), human_bytes((double)eb).c_str());
    if (!s.expert_layers().empty()) {
        const ExpertLayer& el = s.expert_layers()[0];
        printf(" (one expert: %s)", human_bytes((double)el.record_bytes()).c_str());
    }
    printf("\n");
    return 0;
}

int cmd_inspect(const Args& a) {
    a.allow({"layers", "all"});
    const std::string dir = a.need_pos(0, "a checkpoint directory or a store");
    if (file_exists(path_join(dir, "manifest.json"))) return inspect_store(dir);

    StModel m(dir);
    HK_CHECK(m.config().is_obj(), "%s has no config.json", dir.c_str());
    ModelConfig c = ModelConfig::from_json(m.config());
    printf("checkpoint: %s\n", dir.c_str());
    printf("model     : %s\n", c.summary().c_str());
    int present = 0;
    int64_t on_disk = 0;
    for (const auto& s : m.shards()) {
        present += s.present ? 1 : 0;
        on_disk += s.size;
    }
    printf("shards    : %d of %zu on disk, %s\n", present, m.shards().size(), human_bytes((double)on_disk).c_str());

    // every tensor the engine will ask for: there, in a missing shard, or absent
    int ok = 0, missing_shard = 0, absent = 0, bad = 0;
    std::set<std::string> wanted;
    std::vector<std::set<int>> layer_shards((size_t)c.layers);
    auto check = [&](const std::string& name, int layer) {
        wanted.insert(name);
        const StTensor* t = m.find(name);
        if (!t) {
            if (absent++ < 10) printf("  ABSENT   %s\n", name.c_str());
            return;
        }
        if (!t->available()) {
            ++missing_shard;
            return;
        }
        ++ok;
        if (layer >= 0) layer_shards[(size_t)layer].insert(t->shard);
    };
    check(c.n_embed(), -1);
    for (const TensorNeed& n : head_tensors(c)) check(n.name, -1);
    for (int L = 0; L < c.layers; ++L) {
        for (const TensorNeed& n : layer_tensors(c, L)) check(n.name, L);
        if (!c.is_moe(L)) continue;
        for (int e = 0; e < c.n_experts; ++e)
            for (int w = 0; w < 3; ++w) {
                std::string b = c.n_expert(L, e, w);
                if (m.has(b + ".weight_packed")) {
                    check(b + ".weight_packed", L);
                    check(b + ".weight_scale", L);
                    const StTensor* p = m.find(b + ".weight_packed");
                    const int rows = w == 2 ? c.expert_in() : c.moe_inter, cols = w == 2 ? c.moe_inter : c.expert_in();
                    if (p->available() && (p->shape.size() != 2 || p->shape[0] != rows || p->shape[1] != cols / 2)) {
                        if (bad++ < 5) printf("  BAD SHAPE %s\n", p->name.c_str());
                    }
                } else {
                    check(b + ".weight", L);
                }
            }
    }
    printf("tensors   : %d found, %d in shards not on disk, %d absent from the checkpoint, %d with unexpected shapes\n", ok,
           missing_shard, absent, bad);
    int unknown = 0;
    for (const StTensor& t : m.tensors()) {
        if (wanted.count(t.name) || tensor_is_ignorable(c, t.name)) continue;
        if (unknown++ < 10) printf("  UNKNOWN  %s\n", t.name.c_str());
    }
    printf("unknown   : %d checkpoint tensors the engine does not use%s\n", unknown,
           unknown ? "  <- the forward pass may be missing something" : "");
    if (a.has("layers") || a.flag("all")) {
        // which shards hold which layers, to download only what a per-layer test needs
        std::vector<int32_t> want = a.flag("all") ? std::vector<int32_t>() : parse_int_list(a.str("layers"));
        for (int L = 0; L < c.layers; ++L) {
            if (!want.empty() && std::find(want.begin(), want.end(), L) == want.end()) continue;
            printf("layer %3d :", L);
            // names come from the index, the file itself may be absent
            std::set<std::string> files;
            for (const TensorNeed& n : layer_tensors(c, L)) {
                const StTensor* t = m.find(n.name);
                if (t && t->available()) files.insert(m.shards()[(size_t)t->shard].file);
            }
            for (int s : layer_shards[(size_t)L]) files.insert(m.shards()[(size_t)s].file);
            for (const auto& f : files) printf(" %s", f.c_str());
            printf("\n");
        }
    }
    if (absent == 0 && bad == 0 && unknown == 0) printf("layout    : matches what this build expects\n");
    else printf("layout    : DIFFERS from what this build expects, do not trust results before this is understood\n");
    return (absent || bad) ? 2 : 0;
}

int cmd_convert(const Args& a) {
    a.allow({"layers", "requantize", "delete-source", "strict", "allow-missing-head", "batch", "no-space-check"});
    ConvertOptions o;
    o.src = a.need_pos(0, "the checkpoint directory");
    o.dst = a.need_pos(1, "the store directory to create");
    for (int32_t L : parse_int_list(a.str("layers"))) o.layers.push_back(L);
    o.requantize = a.flag("requantize");
    o.delete_source = a.flag("delete-source");
    o.strict = a.flag("strict");
    o.allow_missing_head = a.flag("allow-missing-head");
    o.batch = (int)a.num("batch", 8);
    o.space_check = !a.flag("no-space-check");
    ConvertReport r = convert_checkpoint(o);
    printf("converted : %d trunk tensors (%s), %d expert layers / %d experts (%s) in %.1f s\n", r.trunk_tensors,
           human_bytes((double)r.trunk_bytes).c_str(), r.expert_layers, r.experts, human_bytes((double)r.expert_bytes).c_str(),
           r.seconds);
    if (r.unused_tensors) printf("note      : %d checkpoint tensors were not used (listed above)\n", r.unused_tensors);
    if (r.shards_deleted)
        printf("deleted   : %d source shards (%s)\n", r.shards_deleted, human_bytes((double)r.shards_deleted_bytes).c_str());
    printf("next      : hkimi run %s --drafter <drafter folder> --prompt \"...\"\n", o.dst.c_str());
    return 0;
}

// sweep: real Kimi over a token sequence, for debugging and tests.
//
// --dump-routing: the experts every position was sent to, and their weights.
// Little-endian, read by tools/routing_stats.py:
//   "HKROUTE1", int32 positions P, MoE layers M, experts per token k, experts per layer E
//   int32 layer[M]       the model's number of each MoE layer
//   int32 token[P]       the sequence
//   int32 top1[P]        real Kimi's first choice for the token after each position
//   float32 top1_logp[P]
//   int32 next_rank[P]   rank of the token that really follows (0 = first choice, -1 at the end)
//   for each MoE layer: uint16 expert[P * k], then float32 weight[P * k]
//
// --dump-states: the hidden state after chosen layers, at every position (what the
// drafter reads). "After layer L" is what L hands to L + 1 before any mixing: with
// attention residuals, the running sum of the current block. Read by tools/hk_states.py:
//   "HKSTATE1", int32 positions P, recorded layers M, hidden size d, 0
//   int32 layer[M]       ascending
//   int32 token[P], int32 top1[P], float32 top1_logp[P], int32 next_rank[P]   as above
//   for each recorded layer: float32 x[P * d]
// Written while the sweep runs, so the file can be larger than memory.
namespace {
struct RoutingDump {
    int positions = 0, k = 0, first = 0;   // first: position of row 0 of the sweep in progress
    std::vector<int> layers;
    std::vector<std::vector<uint16_t>> ids;
    std::vector<std::vector<float>> weights;

    void take(int layer, const LayerStates& s) {
        if (!s.expert) return;
        size_t m = 0;
        while (m < layers.size() && layers[m] != layer) ++m;
        if (m == layers.size()) {
            layers.push_back(layer);
            k = s.k;
            ids.emplace_back((size_t)positions * (size_t)k, (uint16_t)0);
            weights.emplace_back((size_t)positions * (size_t)k, 0.0f);
        }
        HK_CHECK(s.k == k && first + s.rows <= positions, "internal: routing rows do not fit the sequence");
        for (size_t i = 0; i < (size_t)s.rows * (size_t)k; ++i) {
            ids[m][(size_t)first * (size_t)k + i] = (uint16_t)s.expert[i];
            weights[m][(size_t)first * (size_t)k + i] = s.weight[i];
        }
    }
};

struct StateDump {
    std::string path;
    std::fstream f;
    int positions = 0, d = 0, first = 0;
    std::vector<int> layers;   // ascending

    int64_t head_bytes() const { return 8 + 16 + 4 * (int64_t)layers.size() + 16 * (int64_t)positions; }
    int64_t bytes() const { return head_bytes() + (int64_t)layers.size() * positions * d * 4; }

    void open(const std::string& file, const std::vector<int>& which, const std::vector<int32_t>& tokens, int hidden) {
        path = file;
        layers = which;
        positions = (int)tokens.size();
        d = hidden;
        f.open(std::filesystem::u8path(path), std::ios::binary | std::ios::in | std::ios::out | std::ios::trunc);
        HK_CHECK(f.good(), "cannot write %s", path.c_str());
        const int32_t head[4] = {positions, (int32_t)layers.size(), d, 0};
        f.write("HKSTATE1", 8);
        f.write((const char*)head, sizeof(head));
        std::vector<int32_t> col(layers.begin(), layers.end());
        f.write((const char*)col.data(), (std::streamsize)(col.size() * 4));
        f.write((const char*)tokens.data(), (std::streamsize)(tokens.size() * 4));
        check();
    }
    void take(int layer, const LayerStates& s) {
        const auto it = std::lower_bound(layers.begin(), layers.end(), layer);
        if (it == layers.end() || *it != layer) return;
        HK_CHECK(s.d == d && first + s.rows <= positions, "internal: state rows do not fit the sequence");
        const int64_t at = head_bytes() + ((int64_t)(it - layers.begin()) * positions + first) * d * 4;
        f.seekp((std::streamoff)at);
        f.write((const char*)s.x, (std::streamsize)((int64_t)s.rows * d * 4));
        check();
    }
    // what real Kimi predicted at every position
    void finish(const std::vector<PosResult>& all) {
        std::vector<int32_t> col((size_t)positions, -1);
        std::vector<float> logp((size_t)positions, 0.0f);
        for (int i = 0; i < positions; ++i) {
            const PosResult& r = all[(size_t)i];
            if (!r.top_id.empty()) col[(size_t)i] = r.top_id[0];
            if (!r.top_logp.empty()) logp[(size_t)i] = r.top_logp[0];
        }
        f.seekp((std::streamoff)(8 + 16 + 4 * (int64_t)layers.size() + 4 * (int64_t)positions));
        f.write((const char*)col.data(), (std::streamsize)(col.size() * 4));
        f.write((const char*)logp.data(), (std::streamsize)(logp.size() * 4));
        for (int i = 0; i < positions; ++i) col[(size_t)i] = all[(size_t)i].next_rank;
        f.write((const char*)col.data(), (std::streamsize)(col.size() * 4));
        f.flush();
        check();
        f.close();
    }
    void check() { HK_CHECK(f.good(), "cannot write %s (is the disk full? the file needs %s)", path.c_str(), human_bytes((double)bytes()).c_str()); }
};

// one observer for both dumps
struct SweepDumps : SweepObserver {
    RoutingDump* routing = nullptr;
    StateDump* states = nullptr;
    void on_layer_states(int layer, const LayerStates& s) override {
        if (routing) routing->take(layer, s);
        if (states) states->take(layer, s);
    }
};

// "all", or layer numbers such as 74,78,82: checked, sorted, no repeats
std::vector<int> parse_layer_list(const std::string& text, int n_layers) {
    std::vector<int> out;
    if (text.empty() || text == "all") {
        for (int L = 0; L < n_layers; ++L) out.push_back(L);
        return out;
    }
    for (int32_t L : parse_int_list(text)) {
        HK_CHECK(L >= 0 && L < n_layers, "--states-layers %d: the model's layers are numbered 0 to %d", L, n_layers - 1);
        out.push_back(L);
    }
    std::sort(out.begin(), out.end());
    out.erase(std::unique(out.begin(), out.end()), out.end());
    HK_CHECK(!out.empty(), "--states-layers: give layer numbers such as 74,78,82 or `all`");
    return out;
}
}  // namespace

int64_t trunk_ram_budget(const Args& a, bool on_by_default) {
    const std::string v = a.str("trunk-ram", on_by_default ? "auto" : "0");
    if (v == "auto") return -1;   // the reader looks at what is free (Reader::keep_trunk)
    const double gb = a.real("trunk-ram", 0);
    HK_CHECK(gb >= 0 && gb <= 4096, "--trunk-ram is the GB of trunk kept in RAM (0 = none), or `auto`");
    return (int64_t)(gb * (double)((int64_t)1 << 30));
}

int cmd_sweep(const Args& a) {
    a.allow({"tokens", "tokens-file", "dump-logits", "dump-routing", "dump-states", "states-layers", "backend", "chunk", "head-chunk",
             "split", "overshoot", "engine", "buffered", "topk", "quiet", "read-ahead", "ahead-threads", "io-depth", "trunk-ram",
             "expert-block", "pin", "copy-ahead"});
    Store store = Store::open(a.need_pos(0, "the store directory"));
    std::vector<int32_t> tokens;
    if (a.has("tokens-file")) tokens = parse_int_list(read_text_file(a.str("tokens-file")));
    else tokens = parse_int_list(a.str("tokens"));
    HK_CHECK(!tokens.empty(), "give token ids with --tokens 1,2,3 or --tokens-file FILE");
    std::unique_ptr<Backend> bk = Backend::create(a.str("backend", "auto"));
    IoOptions io_opt;
    io_opt.engine = a.str("engine", "auto");
    io_opt.direct = !a.flag("buffered");
    ReaderOptions ro;
    ro.io_depth = (int)a.num("io-depth", ro.io_depth);
    io_opt.threads = std::max(io_opt.threads, ro.io_depth);
    std::unique_ptr<IoEngine> io = IoEngine::create(io_opt);
    // the next layers' trunk is read while the device computes
    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");
    std::unique_ptr<IoEngine> ahead_io;
    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);
    }
    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", 5);
    ro.keep_logits = a.has("dump-logits");
    ro.expert_block = a.num("expert-block", 1) != 0;
    ro.pin = a.num("pin", 1) != 0;
    ro.copy_ahead = a.num("copy-ahead", 1) != 0;
    Reader reader(store, *bk, *io, ro);
    reader.read_ahead(ahead_io.get(), ahead);
    // only with --trunk-ram here: a single sweep would fill it for nothing
    const int64_t ram_plan = reader.keep_trunk(trunk_ram_budget(a, false));

    SeqCheckpoint ck;
    std::vector<float> all_logits;
    std::vector<PosResult> all;
    const int n = (int)tokens.size();
    // --split p: sweep [0, p), save the state, sweep [p, n) from it. Must equal one sweep over [0, n).
    std::vector<int> cuts;
    for (int32_t p : parse_int_list(a.str("split"))) {
        HK_CHECK(p > 0 && p < n, "--split %d is outside the sequence", p);
        cuts.push_back(p);
    }
    cuts.push_back(n);
    RoutingDump routing;
    routing.positions = n;
    const bool dump_routing = a.has("dump-routing"), dump_states = a.has("dump-states");
    HK_CHECK(!dump_routing || store.config().n_experts <= 65536, "--dump-routing stores expert numbers in 16 bits");
    HK_CHECK(dump_states || !a.has("states-layers"), "--states-layers goes with --dump-states FILE");
    StateDump states;
    if (dump_states) states.open(a.str("dump-states"), parse_layer_list(a.str("states-layers"), store.config().layers), tokens, store.config().hidden);
    SweepDumps dumps;
    if (dump_routing) dumps.routing = &routing;
    if (dump_states) dumps.states = &states;
    // --overshoot k: every part but the last sweeps k positions past its end, as when drafted
    // tokens are checked. Half of them are the tokens that do follow, the rest are made up, and
    // the checkpoint is put back after the accepted ones. Must again equal one sweep.
    const int over = (int)a.num("overshoot", 0);
    HK_CHECK(over >= 0 && (over == 0 || (!dump_routing && !dump_states)), "--overshoot does not go with --dump-routing or --dump-states");
    const int vocab = store.config().vocab;
    SweepStats total;
    std::vector<SweepStats> parts;
    std::vector<int> part_from, part_to;
    for (int end : cuts) {
        if (end <= ck.pos) continue;   // an earlier part's accepted positions reached past this cut
        SeqJob job;
        job.tokens = &tokens;
        job.ckpt = &ck;
        job.end = end;
        job.save_at = end;
        std::vector<int32_t> drafted;
        const int first = ck.pos;
        int stands = end;              // where the checkpoint belongs when the sweep is over
        if (over > 0 && end < n) {
            stands = end + std::min(over / 2, n - 1 - end);
            drafted.assign(tokens.begin(), tokens.begin() + stands);
            while ((int)drafted.size() < end + over)
                drafted.push_back((int32_t)(((int64_t)tokens[drafted.size() % (size_t)n] * 7 + 3 + (int64_t)drafted.size()) % vocab));
            job.tokens = &drafted;
            job.end = end + over;
            job.keep_tail = true;
        }
        routing.first = states.first = ck.pos;
        SweepStats s = reader.sweep(job, dump_routing || dump_states ? &dumps : nullptr);
        if (job.keep_tail) {
            ck.rewind(stands);
            job.out.resize((size_t)(stands - first));
            if (!job.logits.empty()) job.logits.resize((size_t)(stands - first) * (size_t)vocab);
            // the last kept position was told a made-up token follows: say what really does
            PosResult& last = job.out.back();
            last.next = tokens[(size_t)stands];
            last.next_rank = -1;
            for (size_t i = 0; i < last.top_id.size(); ++i)
                if (last.top_id[i] == last.next) last.next_rank = (int)i;
        }
        parts.push_back(s);
        part_from.push_back(first);
        part_to.push_back(stands);
        total.add(s);
        all.insert(all.end(), job.out.begin(), job.out.end());
        all_logits.insert(all_logits.end(), job.logits.begin(), job.logits.end());
    }
    // files first: the prints below can be cut short by a closed pipe (| head)
    if (dump_states) states.finish(all);
    if (a.has("dump-logits")) {
        std::ofstream f(std::filesystem::u8path(a.str("dump-logits")), std::ios::binary | std::ios::trunc);
        f.write((const char*)all_logits.data(), (std::streamsize)(all_logits.size() * 4));
        HK_CHECK(f.good(), "cannot write %s", a.str("dump-logits").c_str());
    }
    if (dump_routing) {
        std::ofstream f(std::filesystem::u8path(a.str("dump-routing")), std::ios::binary | std::ios::trunc);
        auto put = [&f](const void* p, size_t bytes) { f.write((const char*)p, (std::streamsize)bytes); };
        const int32_t head[4] = {n, (int32_t)routing.layers.size(), routing.k, store.config().n_experts};
        put("HKROUTE1", 8);
        put(head, sizeof(head));
        std::vector<int32_t> col(routing.layers.begin(), routing.layers.end());
        put(col.data(), col.size() * 4);
        put(tokens.data(), (size_t)n * 4);
        std::vector<float> logp((size_t)n);
        col.assign((size_t)n, -1);
        for (int i = 0; i < n; ++i) {
            const PosResult& r = all[(size_t)i];
            if (!r.top_id.empty()) col[(size_t)i] = r.top_id[0];
            logp[(size_t)i] = r.top_logp.empty() ? 0.0f : r.top_logp[0];
        }
        put(col.data(), (size_t)n * 4);
        put(logp.data(), (size_t)n * 4);
        for (int i = 0; i < n; ++i) col[(size_t)i] = all[(size_t)i].next_rank;
        put(col.data(), (size_t)n * 4);
        for (size_t m = 0; m < routing.layers.size(); ++m) {
            put(routing.ids[m].data(), routing.ids[m].size() * 2);
            put(routing.weights[m].data(), routing.weights[m].size() * 4);
        }
        HK_CHECK(f.good(), "cannot write %s", a.str("dump-routing").c_str());
    }
    if (!a.flag("quiet")) {
        printf("backend %s, io %s%s%s: %d positions in %.2f s, %s read, %d expert reads\n", bk->name(), io->name(),
               ahead > 0 ? strfmt(", reading %d layer%s ahead", ahead, ahead == 1 ? "" : "s").c_str() : "",
               ram_plan > 0 ? strfmt(", %s of the trunk kept in RAM", human_bytes((double)ram_plan).c_str()).c_str() : "", n,
               total.seconds, human_bytes((double)total.bytes_read).c_str(), total.expert_reads);
        if (total.ram_bytes > 0)
            printf("not read: %s of trunk that came from RAM (%s held at the end)\n", human_bytes((double)total.ram_bytes).c_str(),
                   human_bytes((double)reader.trunk_kept_bytes()).c_str());
        if (total.ahead_bytes > 0)
            printf("copied ahead: %s of trunk was on its way to the device before its layer began (%.2f s went into sending it off)\n",
                   human_bytes((double)total.ahead_bytes).c_str(), total.ahead_seconds);
        if (bk->mem_peak() > 0)
            printf("device memory: at most %s held at one time, of the card's %s\n", human_bytes((double)bk->mem_peak()).c_str(),
                   human_bytes((double)bk->mem_total()).c_str());
        if (process_ram_peak_bytes() > 0)
            printf("RAM: this process held at most %s at one time\n", human_bytes((double)process_ram_peak_bytes()).c_str());
        printf("of which: loading the trunk %.2f s, routed experts (reading and computing) %.2f s, output head %.2f s\n",
               total.io_seconds, total.expert_seconds, total.head_seconds);
        const double rest = total.seconds - total.io_seconds - total.expert_seconds - total.head_seconds - total.attn_seconds -
                            total.post_seconds - total.free_seconds;
        printf("in detail: experts waiting for the disk %.2f s and computing %.2f s, attention %.2f s, after the experts %.2f s, "
               "freeing weights %.2f s, everything else %.2f s\n",
               total.expert_wait_seconds, total.expert_seconds - total.expert_wait_seconds, total.attn_seconds, total.post_seconds,
               total.free_seconds, rest);
        printf("loading trunk and head: %.2f s waiting for the disk, %.2f s copying to the device\n", total.trunk_wait_seconds,
               total.trunk_copy_seconds);
        if (dump_states)
            printf("states after %zu layer%s written to %s (%s)\n", states.layers.size(), states.layers.size() == 1 ? "" : "s",
                   states.path.c_str(), human_bytes((double)states.bytes()).c_str());
        // with --split each part is a sweep of its own
        for (size_t i = 0; cuts.size() > 1 && i < parts.size(); ++i) {
            const SweepStats& p = parts[i];
            printf("part [%4d, %4d): %4d positions in %7.2f s, %s read%s, %d expert reads%s\n", part_from[i], part_to[i], p.positions,
                   p.seconds, human_bytes((double)p.bytes_read).c_str(),
                   p.ram_bytes > 0 ? strfmt(" and %s from RAM", human_bytes((double)p.ram_bytes).c_str()).c_str() : "", p.expert_reads,
                   p.ahead_bytes > 0 ? strfmt(", %s of trunk copied ahead", human_bytes((double)p.ahead_bytes).c_str()).c_str() : "");
            printf("      of its seconds: trunk %.2f (waiting for the disk %.2f, copying to the device %.2f), experts %.2f (%.2f of them "
                   "waiting for the disk), attention %.2f, after the experts %.2f, freeing %.2f, head %.2f, else %.2f\n",
                   p.io_seconds, p.trunk_wait_seconds, p.trunk_copy_seconds, p.expert_seconds, p.expert_wait_seconds, p.attn_seconds,
                   p.post_seconds, p.free_seconds, p.head_seconds,
                   p.seconds - p.io_seconds - p.expert_seconds - p.attn_seconds - p.post_seconds - p.free_seconds - p.head_seconds);
        }
        for (int i = 0; i < n; ++i) {
            const PosResult& r = all[(size_t)i];
            printf("pos %4d tok %6d -> top", i, tokens[(size_t)i]);
            for (size_t j = 0; j < r.top_id.size() && j < 3; ++j) printf(" %d(%.3f)", r.top_id[j], r.top_logp[j]);
            if (r.next >= 0) printf("   next %d logp %.3f rank %d", r.next, r.next_logp, r.next_rank);
            printf("\n");
        }
    }
    return 0;
}

}  // namespace hk