File size: 36,431 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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
#include "format/store_io.h"

#include <condition_variable>
#include <exception>
#include <cstring>
#include <mutex>
#include <thread>

#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<std::string> names;
        std::vector<Item> 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<std::unique_ptr<Job>> plan;      // in the order the loads will be asked for
    std::vector<std::unique_ptr<Job>> leaving;   // dropped while still being read or used
    std::vector<AlignedBuf> pool;                // depth + 1 buffers, each grows to the largest load it held
    std::vector<int> 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<Job> 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<std::mutex> 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<Ahead> 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<TrunkPlan>& 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<std::unique_ptr<Ahead::Job>> fresh(upcoming.size());
    for (size_t u = 0; u < upcoming.size() && (int)u <= a.depth; ++u) {
        std::unique_ptr<Ahead::Job> 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<std::mutex> lk(a.mu);
        std::vector<std::unique_ptr<Ahead::Job>> next;
        for (size_t u = 0; u < fresh.size(); ++u) {
            if (!fresh[u]) continue;
            std::unique_ptr<Ahead::Job> 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<std::mutex> 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<std::string>& names, int key) {
    Ahead& a = *ahead_;
    std::lock_guard<std::mutex> 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<std::mutex> 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<std::string>& names, int key, std::vector<Weight*>& 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<std::mutex> 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<int64_t> 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<std::mutex> 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<int>& keys) {
    std::unordered_map<int, Kept> 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<Weight*> StoreIo::load_kept(Backend& bk, const Kept& k) {
    std::vector<Weight*> 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<std::string>& names, const std::vector<int64_t>& 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<std::string>& 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<std::mutex> 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<Weight*> 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<std::mutex> 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<int64_t> 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<std::mutex> 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<Weight*> 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<Weight*> 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<uint8_t>& 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<Weight*> StoreIo::load_trunk_many(Backend& bk, const std::vector<std::string>& 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<Weight*> 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<Item> 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<Weight*> 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<int64_t> 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<uint8_t> 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