File size: 33,264 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
#include "reader/reader.h"

#include "io/os_info.h"

#include <algorithm>
#include <cmath>
#include <cstring>

#include "common/base.h"

namespace hk {

void SeqCheckpoint::reset(const ModelConfig& c) {
    pos = 0;
    tail = 0;
    dim_hd = c.kda_heads * c.kda_dim;
    dim_h = c.kda_heads;
    dim_c = c.kv_lora;
    dim_r = c.rope;
    dim_keys = c.idx_dim;
    const size_t n = (size_t)c.layers;
    kda_tail.assign(n, KdaTail());
    kda_S.assign(n, {});
    kda_ring.assign(n, {});
    mla_C.assign(n, {});
    mla_R.assign(n, {});
    mla_keys.assign(n, {});
    const size_t HD = (size_t)c.kda_heads * (size_t)c.kda_dim;
    for (int L = 0; L < c.layers; ++L) {
        if (!c.is_kda(L)) continue;
        kda_S[(size_t)L].assign(HD * (size_t)c.kda_dim, 0.0f);
        kda_ring[(size_t)L].assign(3 * (size_t)(c.conv_k - 1) * HD, 0.0f);
    }
}

int64_t SeqCheckpoint::bytes() const {
    int64_t n = 0;
    for (const auto* v : {&kda_S, &kda_ring, &mla_C, &mla_R, &mla_keys})
        for (const auto& x : *v) n += (int64_t)x.size() * 4;
    for (const KdaTail& t : kda_tail) n += t.bytes();
    return n;
}

void SeqCheckpoint::rewind(int new_pos) {
    HK_CHECK(new_pos <= pos && new_pos >= pos - tail, "a checkpoint at position %d that can go back %d cannot be moved to %d", pos, tail,
             new_pos);
    const int keep = tail - (pos - new_pos);
    for (size_t L = 0; L < kda_tail.size(); ++L) {
        if (!kda_S[L].empty()) kda_tail[L].truncate(keep, dim_hd, dim_h);
        if (!mla_C[L].empty()) mla_C[L].resize((size_t)new_pos * (size_t)dim_c);
        if (!mla_R[L].empty()) mla_R[L].resize((size_t)new_pos * (size_t)dim_r);
        if (!mla_keys[L].empty()) mla_keys[L].resize((size_t)new_pos * (size_t)dim_keys);
    }
    tail = keep;
    pos = new_pos;
}

void logits_stats(const float* lg, int V, int topk, int32_t next, PosResult& out) {
    float mx = lg[0];
    for (int i = 1; i < V; ++i) mx = std::max(mx, lg[i]);
    double sum = 0, sum_pl = 0;
    for (int i = 0; i < V; ++i) {
        double e = std::exp((double)lg[i] - mx);
        sum += e;
        sum_pl += e * lg[i];
    }
    const double logZ = (double)mx + std::log(sum);
    out.entropy = (float)(logZ - sum_pl / sum);
    // top-k by a small insertion list (k is tiny next to the vocabulary)
    topk = std::min(topk, V);
    out.top_id.assign((size_t)topk, -1);
    out.top_logp.assign((size_t)topk, -1e30f);
    for (int i = 0; i < V; ++i) {
        if (lg[i] <= out.top_logp[(size_t)topk - 1]) continue;
        int j = topk - 1;
        while (j > 0 && out.top_logp[(size_t)j - 1] < lg[i]) {
            out.top_logp[(size_t)j] = out.top_logp[(size_t)j - 1];
            out.top_id[(size_t)j] = out.top_id[(size_t)j - 1];
            --j;
        }
        out.top_logp[(size_t)j] = lg[i];
        out.top_id[(size_t)j] = i;
    }
    for (int j = 0; j < topk; ++j) out.top_logp[(size_t)j] = (float)(out.top_logp[(size_t)j] - logZ);
    out.next = next;
    if (next >= 0 && next < V) {
        out.next_logp = (float)(lg[next] - logZ);
        int rank = 0;
        for (int i = 0; i < V; ++i) rank += lg[i] > lg[next] ? 1 : 0;
        out.next_rank = rank;
    } else {
        out.next_logp = 0;
        out.next_rank = -1;
    }
}

struct Reader::Impl {
    StoreIo sio;
    std::unique_ptr<WeightSet> head;   // the output head, when it is kept between sweeps
    // The buffers expert records are read into, kept from layer to layer and sweep to sweep:
    // mapping fresh memory page by page under the disk's writes cost about 4 s of every sweep.
    std::vector<AlignedBuf> expert_bufs;
    // which of them the backend holds page-locked; unlocked before being freed or grown
    std::vector<uint8_t> expert_pinned;
    Backend* pin_bk = nullptr;
    bool pin_refused = false;   // the backend said no once (no GPU, or the system refuses): not asked again
    Impl(const Store& s, IoEngine& io) : sio(s, io) {}
    ~Impl() {
        for (size_t i = 0; i < expert_bufs.size(); ++i)
            if (i < expert_pinned.size() && expert_pinned[i]) pin_bk->unpin(expert_bufs[i].data());
    }
    // buffer i with room for `bytes`, page-locked when `pin` and the backend can
    void expert_buf(Backend& bk, size_t i, int64_t bytes, bool pin) {
        if (expert_bufs.size() <= i) expert_bufs.resize(i + 1);
        if (expert_pinned.size() < expert_bufs.size()) expert_pinned.resize(expert_bufs.size(), 0);
        AlignedBuf& b = expert_bufs[i];
        const bool want = pin && !pin_refused;
        if (b.size() >= bytes && (expert_pinned[i] != 0) == want) return;
        if (expert_pinned[i]) {
            pin_bk->unpin(b.data());
            expert_pinned[i] = 0;
        }
        b.reserve(bytes);
        if (!want) return;
        if (bk.pin(b.data(), b.size())) {
            expert_pinned[i] = 1;
            pin_bk = &bk;
        } else {
            pin_refused = true;
        }
    }

    // reads the head's tensors into `hs`
    void load_head(Backend& bk, const ModelConfig& c, WeightSet& hs) {
        std::vector<std::string> names;
        for (const TensorNeed& n : head_tensors(c)) names.push_back(n.name);
        std::vector<Weight*> loaded = sio.load_trunk_many(bk, names);
        for (size_t i = 0; i < names.size(); ++i) hs.put(names[i], loaded[i]);
    }
    const WeightSet& kept_head(Backend& bk, const ModelConfig& c) {
        if (!head) {
            std::unique_ptr<WeightSet> hs(new WeightSet(&bk));
            load_head(bk, c, *hs);
            head = std::move(hs);
            sio.drop_buffers();   // 2.3 GB that this one load needed and no later one will
        }
        return *head;
    }
};

Reader::Reader(const Store& store, Backend& bk, IoEngine& io, const ReaderOptions& opt)
    : store_(store), bk_(bk), opt_(opt), impl_(new Impl(store, io)) {}
Reader::~Reader() = default;

StoreIo& Reader::store_io() { return impl_->sio; }
bool Reader::copies_ahead() { return impl_->sio.can_copy_ahead(); }

void Reader::read_ahead(IoEngine* io, int depth) {
    // With copying ahead the read-ahead buffers are made once, each the size of the largest
    // layer's trunk, and page-locked. --pin 0 turns it off as well.
    Backend* copy_bk = opt_.copy_ahead && opt_.pin && bk_.can_load_async() ? &bk_ : nullptr;
    int64_t largest = 0;
    if (copy_bk) {
        const ModelConfig& c = config();
        const int L_first = std::max(0, opt_.first_layer);
        const int L_last = opt_.last_layer < 0 ? c.layers - 1 : std::min(opt_.last_layer, c.layers - 1);
        for (int l = L_first; l <= L_last; ++l) {
            int64_t s = 0;
            for (const TensorNeed& n : layer_tensors(c, l)) s += align_up(store_.get(n.name).nbytes);
            largest = std::max(largest, s);
        }
    }
    impl_->sio.enable_read_ahead(io, depth, copy_bk, largest);
}

int64_t Reader::keep_trunk(int64_t budget) {
    const ModelConfig& c = config();
    const int L_first = std::max(0, opt_.first_layer);
    const int L_last = opt_.last_layer < 0 ? c.layers - 1 : std::min(opt_.last_layer, c.layers - 1);
    std::vector<int64_t> size;
    int64_t total = 0;
    for (int l = L_first; l <= L_last; ++l) {
        int64_t s = 0;
        for (const TensorNeed& n : layer_tensors(c, l)) s += align_up(store_.get(n.name).nbytes);
        size.push_back(s);
        total += s;
    }
    if (budget < 0) {
        // Not told how much: what is free now, less what the rest needs (working memory, read-ahead
        // buffers, the drafter, air for the system). With 56 GB free that is 40 GB of K3.1 Pro's
        // 111.5. A model whose whole trunk is small next to the free RAM is kept whole.
        const int64_t reserve = (int64_t)16 << 30;
        const int64_t free = system_ram_free_bytes();
        if (free < 0) budget = 0;   // unknown: nothing, rather than a guess
        else if (total <= free / 4) budget = total;
        else budget = free > reserve ? free - reserve : 0;
    }
    std::vector<int> keys;
    int64_t kept = 0;
    if (budget > 0 && total > 0) {
        // Each layer's share of the budget adds up, and a layer is taken every time a whole layer's
        // worth has come together: with a third of the trunk, about every third layer.
        const double share = std::min(1.0, (double)budget / (double)total);
        double credit = 0;
        for (size_t i = 0; i < size.size(); ++i) {
            credit += share * (double)size[i];
            if (size[i] > 0 && credit + 0.5 >= (double)size[i]) {
                credit -= (double)size[i];
                keys.push_back(L_first + (int)i);
                kept += size[i];
            }
        }
    }
    impl_->sio.keep_in_ram(keys);
    return kept;
}

int64_t Reader::trunk_kept_bytes() { return impl_->sio.ram_held(); }

const Weight* Reader::lm_head() {
    HK_CHECK(opt_.keep_head, "internal: the reader was not asked to keep its output head");
    return impl_->kept_head(bk_, config()).get(config().n_lm_head());
}

namespace {

struct Chunk {
    int job, a, b;   // positions [a, b) of jobs[job]
    int row0;        // flat row of position a
};

Weight* load_planes(Backend& bk, const PlanesDesc& pd, const PlanesView& pv) {
    WeightDesc d;
    d.fmt = WFmt::PLANES;
    d.rows = pd.rows;
    d.cols = pd.cols;
    d.planes = pd;
    WeightData data;
    data.planes = pv;
    return bk.load(d, data);
}

}  // namespace

SweepStats Reader::sweep(std::vector<SeqJob*>& jobs, SweepObserver* obs) {
    const double t_start = now_sec();
    SweepStats st;
    const ModelConfig& c = config();
    const int d = c.hidden;
    StoreIo& sio = impl_->sio;
    const int64_t bytes0 = sio.bytes_read(), ram0 = sio.bytes_from_ram(), ahead0 = sio.bytes_ahead();
    const double wait0 = sio.trunk_wait_seconds(), copy0 = sio.trunk_copy_seconds();
    LinHook* hook = obs ? obs->lin_hook() : nullptr;

    // ---- lay the jobs out as flat rows and cut them into chunks -----------------
    std::vector<int> base(jobs.size());
    std::vector<Chunk> chunks;
    int N = 0;
    for (size_t j = 0; j < jobs.size(); ++j) {
        SeqJob& job = *jobs[j];
        HK_CHECK(job.tokens && job.ckpt, "sweep job %zu has no tokens or checkpoint", j);
        SeqCheckpoint& ck = *job.ckpt;
        if (ck.kda_S.empty()) {
            HK_CHECK(ck.pos == 0, "sweep job %zu: checkpoint at position %d has no state", j, ck.pos);
            ck.reset(c);
        }
        HK_CHECK(ck.pos >= 0 && ck.pos <= job.end && job.end <= (int)job.tokens->size(),
                 "sweep job %zu: bad range [%d, %d) for %zu tokens", j, ck.pos, job.end, job.tokens->size());
        if (job.keep_tail) job.save_at = job.end;   // the tail is what lets it be moved back afterwards
        HK_CHECK(job.save_at < 0 || (job.save_at >= ck.pos && job.save_at <= job.end),
                 "sweep job %zu: save_at %d is outside [%d, %d]", j, job.save_at, ck.pos, job.end);
        base[j] = N;
        int a = ck.pos;
        while (a < job.end) {
            int b = std::min(job.end, a + std::max(1, opt_.chunk));
            // a chunk boundary at the new checkpoint (not with a tail: the KDA states are then taken before the first chunk)
            if (!job.keep_tail && job.save_at > a && job.save_at < b) b = job.save_at;
            chunks.push_back({(int)j, a, b, N + (a - ck.pos)});
            a = b;
        }
        N += job.end - ck.pos;
        job.out.clear();
        job.logits.clear();
    }
    st.positions = N;
    if (obs) {
        std::vector<int> row_job((size_t)N);
        for (size_t j = 0; j < jobs.size(); ++j)
            for (int r = base[j]; r < base[j] + (jobs[j]->end - jobs[j]->ckpt->pos); ++r) row_job[(size_t)r] = (int)j;
        obs->on_sweep_begin(row_job);
    }

    std::vector<SeqCheckpoint> staged(jobs.size());
    for (size_t j = 0; j < jobs.size(); ++j)
        if (jobs[j]->save_at >= 0) {
            staged[j].reset(c);
            staged[j].pos = jobs[j]->save_at;
            if (jobs[j]->keep_tail) staged[j].tail = jobs[j]->end - jobs[j]->ckpt->pos;
        }
    if (N == 0) {
        // nothing to compute; a checkpoint can only "move" to where it already is
        st.seconds = now_sec() - t_start;
        return st;
    }

    // ---- embeddings ---------------------------------------------------------------
    std::vector<float> X((size_t)N * (size_t)d);
    for (size_t j = 0; j < jobs.size(); ++j) {
        const SeqJob& job = *jobs[j];
        int n = job.end - job.ckpt->pos;
        if (n <= 0) continue;
        if (opt_.hidden_io) {
            HK_CHECK(job.hidden_in && job.hidden_in->size() == (size_t)n * (size_t)d, "sweep job %zu: hidden_in must be [%d, %d]", j, n, d);
            memcpy(X.data() + (size_t)base[j] * (size_t)d, job.hidden_in->data(), job.hidden_in->size() * 4);
        } else {
            sio.embed(job.tokens->data() + job.ckpt->pos, n, X.data() + (size_t)base[j] * (size_t)d);
        }
    }

    std::vector<std::vector<float>> hblocks;   // AttnRes block history on the host, each [N, d]
    const int in_dim = c.expert_in();
    const int k = c.top_k;
    const Act act = act_of(c);
    const int L_first = std::max(0, opt_.first_layer);
    const int L_last = opt_.last_layer < 0 ? c.layers - 1 : std::min(opt_.last_layer, c.layers - 1);
    if (c.ares_block > 0 && L_first > 0) {
        // A layer test that starts in the middle: the layers before would have stored this many
        // blocks. Stand-ins of the right shape are made from the input.
        const int nb = (L_first + c.ares_block - 1) / c.ares_block;
        for (int b = 0; b < nb; ++b) {
            hblocks.emplace_back(X);
            const float f = 0.5f + 0.25f * (float)b;
            for (float& v : hblocks.back()) v *= f;
        }
    }

    for (int L = L_first; L <= L_last; ++L) {
        if (obs) obs->on_layer_begin(L);
        // ---- this layer's trunk, from disk to the device ------------------------
        double t_io = now_sec();
        WeightSet ws(&bk_);
        std::vector<TensorNeed> needs = layer_tensors(c, L);
        if (sio.ahead_depth() > 0) {
            // Tell the reading thread what comes after this layer. After the last layer comes the first
            // again: the next sweep's first layers are read while this one ends. Layers kept in RAM
            // need no reading.
            std::vector<TrunkPlan> upcoming;
            int l = L;
            do {
                if (!sio.in_ram(l)) {
                    TrunkPlan p;
                    p.key = l;
                    for (const TensorNeed& n : layer_tensors(c, l)) p.names.push_back(n.name);
                    upcoming.push_back(std::move(p));
                }
                l = l < L_last ? l + 1 : L_first;
            } while (l != L && (int)upcoming.size() <= sio.ahead_depth());
            sio.plan_ahead(upcoming);
        }
        {
            // all of the layer at once: the reads overlap each other and the copies to the device
            std::vector<std::string> names;
            for (const TensorNeed& n : needs) names.push_back(n.name);
            std::vector<Weight*> loaded = sio.load_trunk_many(bk_, names, L);
            for (size_t i = 0; i < names.size(); ++i) ws.put(names[i], loaded[i]);
        }
        st.io_seconds += now_sec() - t_io;
        LayerW w = bind_layer(c, L, ws);
        const bool kda = w.kda, moe = w.moe;
        const bool new_block = c.ares_block > 0 && (L % c.ares_block) == 0;
        const size_t nb_before = hblocks.size();
        if (new_block) hblocks.emplace_back((size_t)N * (size_t)d);

        std::vector<float> H2, RES, XLAT, YLAT, lg;
        std::vector<int32_t> ridx;
        std::vector<float> rw;
        if (moe) {
            H2.resize((size_t)N * (size_t)d);
            RES.resize((size_t)N * (size_t)d);
            XLAT.resize((size_t)N * (size_t)in_dim);
            YLAT.assign((size_t)N * (size_t)in_dim, 0.0f);
            ridx.resize((size_t)N * (size_t)k);
            rw.resize((size_t)N * (size_t)k);
        }
        std::vector<float> bias_host;
        if (moe) {
            const double t_bias = now_sec();
            const TrunkEntry& be = store_.get(c.n_layer(L, "block_sparse_moe.gate.e_score_correction_bias"));
            bias_host.resize((size_t)be.numel());
            std::vector<uint8_t> raw;
            sio.read_trunk(be, raw);
            decode_to_f32(be.dtype, raw.data(), be.numel(), bias_host.data());
            st.io_seconds += now_sec() - t_bias;
        }

        // ---- phase A: attention (and the dense MLP) for every chunk --------------
        const double t_attn = now_sec();
        size_t ci = 0;
        for (size_t j = 0; j < jobs.size(); ++j) {
            SeqJob& job = *jobs[j];
            SeqCheckpoint& ck = *job.ckpt;
            const int HD = c.kda_heads * c.kda_dim, K1 = c.conv_k - 1;
            KdaState ks;
            MlaState ms;
            // where the KDA states of the new checkpoint are taken: before the first chunk when the sweep keeps a tail
            const int kda_save = job.keep_tail ? ck.pos : job.save_at;
            auto stage_kda = [&]() {
                staged[j].kda_S[(size_t)L].resize((size_t)HD * (size_t)c.kda_dim);
                bk_.download(ks.S, 0, HD, staged[j].kda_S[(size_t)L].data());
                staged[j].kda_ring[(size_t)L].resize(3 * (size_t)K1 * (size_t)HD);
                for (int i = 0; i < 3; ++i) bk_.download(ks.ring[i], 0, K1, staged[j].kda_ring[(size_t)L].data() + (size_t)i * K1 * HD);
            };
            if (kda) {
                ks.init(bk_, c);
                bk_.upload(ks.S, 0, HD, ck.kda_S[(size_t)L].data());
                for (int i = 0; i < 3; ++i) bk_.upload(ks.ring[i], 0, K1, ck.kda_ring[(size_t)L].data() + (size_t)i * K1 * HD);
                // a checkpoint that was moved back: its states are carried over the positions it kept
                if (ck.tail > 0) kda_replay(bk_, c, w.kdaw, ck.kda_tail[(size_t)L], ck.tail, ks);
                if (kda_save == ck.pos) {
                    if (ck.tail > 0) {
                        stage_kda();
                    } else {
                        staged[j].kda_S[(size_t)L] = ck.kda_S[(size_t)L];
                        staged[j].kda_ring[(size_t)L] = ck.kda_ring[(size_t)L];
                    }
                }
            } else if (ck.pos > 0) {
                ms.reserve(bk_, c, c.is_dsa(L), job.end);
                bk_.upload(ms.C, 0, ck.pos, ck.mla_C[(size_t)L].data());
                bk_.upload(ms.R, 0, ck.pos, ck.mla_R[(size_t)L].data());
                if (c.is_dsa(L)) bk_.upload(ms.keys, 0, ck.pos, ck.mla_keys[(size_t)L].data());
                ms.len = ck.pos;
            }
            for (; ci < chunks.size() && chunks[ci].job == (int)j; ++ci) {
                const Chunk& ch = chunks[ci];
                const int T = ch.b - ch.a;
                const size_t r0 = (size_t)ch.row0;
                TensorRef x(&bk_, T, d);
                bk_.upload(x, 0, T, X.data() + r0 * d);
                std::vector<Tensor*> blocks;
                struct BlockGuard {   // device copies of the block history for these rows
                    Backend& bk;
                    std::vector<Tensor*>& v;
                    ~BlockGuard() {
                        for (Tensor* t : v) bk.release(t);
                    }
                } guard{bk_, blocks};
                for (size_t i = 0; i < nb_before; ++i) {
                    Tensor* t = bk_.alloc(T, d);
                    blocks.push_back(t);
                    bk_.upload(t, 0, T, hblocks[i].data() + r0 * d);
                }
                PreOut po;
                if (obs) obs->on_chunk(ch.job, ch.a, ch.b);
                layer_pre(bk_, c, w, x, blocks, kda ? &ks : nullptr, kda ? nullptr : &ms, po, hook,
                          kda && job.keep_tail ? &staged[j].kda_tail[(size_t)L] : nullptr);
                if (new_block) bk_.download(blocks.back(), 0, T, hblocks.back().data() + r0 * d);
                if (po.done) {
                    bk_.download(x, 0, T, X.data() + r0 * d);
                } else {
                    bk_.download(po.h2, 0, T, H2.data() + r0 * d);
                    bk_.download(po.res, 0, T, RES.data() + r0 * d);
                    bk_.download(c.latent > 0 ? po.xlat.get() : po.h2.get(), 0, T, XLAT.data() + r0 * in_dim);
                    lg.resize((size_t)T * (size_t)c.n_experts);
                    bk_.download(po.logits, 0, T, lg.data());
                    Routing rt;
                    moe_route(c, lg.data(), bias_host.data(), T, rt);
                    memcpy(ridx.data() + r0 * k, rt.idx.data(), rt.idx.size() * sizeof(int32_t));
                    memcpy(rw.data() + r0 * k, rt.w.data(), rt.w.size() * sizeof(float));
                }
                if (kda && kda_save == ch.b) stage_kda();
            }
            if (!kda && job.save_at > 0) {
                // the device cache now holds the latents of every position; keep those before the new checkpoint
                const int n = job.save_at;
                HK_CHECK(ms.len >= n, "internal: attention cache shorter than the checkpoint");
                staged[j].mla_C[(size_t)L].resize((size_t)n * (size_t)c.kv_lora);
                staged[j].mla_R[(size_t)L].resize((size_t)n * (size_t)c.rope);
                bk_.download(ms.C, 0, n, staged[j].mla_C[(size_t)L].data());
                bk_.download(ms.R, 0, n, staged[j].mla_R[(size_t)L].data());
                if (c.is_dsa(L)) {
                    staged[j].mla_keys[(size_t)L].resize((size_t)n * (size_t)c.idx_dim);
                    bk_.download(ms.keys, 0, n, staged[j].mla_keys[(size_t)L].data());
                }
            }
        }
        bk_.sync();   // so that the device's work is counted where it was asked for
        st.attn_seconds += now_sec() - t_attn;
        // attention weights are not needed again in this layer
        {
            const double t_free = now_sec();
            for (const TensorNeed& n : needs)
                if (n.part == Part::Attn) ws.erase(n.name);
            st.free_seconds += now_sec() - t_free;
        }

        if (moe) {
            // ---- phase B: each needed expert is read once and applied to all its rows ----
            const double t_exp = now_sec();
            const ExpertLayer& el = store_.experts(L);
            HK_CHECK(el.in_dim == in_dim && el.inter == c.moe_inter && el.n_experts == c.n_experts,
                     "layer %d: the expert file does not match the model config", L);
            const int file = sio.expert_file(L);
            std::vector<std::vector<int32_t>> rows_of((size_t)c.n_experts);
            std::vector<std::vector<float>> coef_of((size_t)c.n_experts);
            for (int r = 0; r < N; ++r)
                for (int j = 0; j < k; ++j) {
                    int e = ridx[(size_t)r * k + j];
                    rows_of[(size_t)e].push_back(r);
                    coef_of[(size_t)e].push_back(rw[(size_t)r * k + j]);
                }
            std::vector<int> needed;
            for (int e = 0; e < c.n_experts; ++e)
                if (!rows_of[(size_t)e].empty()) needed.push_back(e);
            const int64_t rec = el.record_bytes();
            const int nbuf = std::max(1, std::min<int>(opt_.io_depth, (int)needed.size()));
            std::vector<int> free_bufs;
            for (int i = 0; i < nbuf; ++i) {
                impl_->expert_buf(bk_, (size_t)i, rec, opt_.pin);
                free_bufs.push_back(i);
            }
            std::vector<AlignedBuf>& bufs = impl_->expert_bufs;
            IoEngine& io = sio.io();
            // Reads are issued in expert order, up to nbuf at a time, and may complete in any order.
            // Experts are applied strictly in expert order all the same, so the sum over a token's
            // experts is always formed the same way.
            size_t next = 0, proc = 0;
            std::vector<int> buf_of(needed.size(), -1);
            std::vector<uint8_t> ready(needed.size(), 0);
            std::vector<float> xc, yc;
            // meanwhile the next layer's trunk starts for the card: every time round the loop below,
            // whatever of it is in memory by then
            std::vector<std::string> next_trunk;
            if (opt_.copy_ahead && L < L_last && sio.can_copy_ahead())
                for (const TensorNeed& n : layer_tensors(c, L + 1)) next_trunk.push_back(n.name);
            auto apply_expert = [&](size_t seq) {
                const int e = needed[seq], b = buf_of[seq];
                ExpertViews v = expert_views(el, bufs[(size_t)b].data(), 4);
                Weight* three[3] = {nullptr, nullptr, nullptr};
                if (opt_.expert_block) {
                    // the whole record at once: gate, up and down are views into one block on the device
                    WeightDesc wdesc[3];
                    WeightData wdata[3];
                    for (int m = 0; m < 3; ++m) {
                        wdesc[m].fmt = WFmt::PLANES;
                        wdesc[m].rows = v.desc[m].rows;
                        wdesc[m].cols = v.desc[m].cols;
                        wdesc[m].planes = v.desc[m];
                        wdata[m].planes = v.view[m];
                    }
                    bk_.load_block(wdesc, wdata, 3, bufs[(size_t)b].data(), rec, three);
                }
                WeightRef wg(&bk_, three[0] ? three[0] : load_planes(bk_, v.desc[0], v.view[0]));
                WeightRef wu(&bk_, three[1] ? three[1] : load_planes(bk_, v.desc[1], v.view[1]));
                WeightRef wd(&bk_, three[2] ? three[2] : load_planes(bk_, v.desc[2], v.view[2]));
                const std::vector<int32_t>& rows = rows_of[(size_t)e];
                const int n = (int)rows.size();
                xc.resize((size_t)n * (size_t)in_dim);
                yc.resize((size_t)n * (size_t)in_dim);
                for (int r = 0; r < n; ++r)
                    memcpy(xc.data() + (size_t)r * in_dim, XLAT.data() + (size_t)rows[(size_t)r] * in_dim, (size_t)in_dim * 4);
                TensorRef txc(&bk_, n, in_dim), tyc(&bk_, n, in_dim);
                bk_.upload(txc, 0, n, xc.data());
                expert_forward(bk_, act, wg, wu, wd, txc, tyc);
                bk_.download(tyc, 0, n, yc.data());
                for (int r = 0; r < n; ++r) {
                    float* dst = YLAT.data() + (size_t)rows[(size_t)r] * in_dim;
                    const float* srcp = yc.data() + (size_t)r * in_dim;
                    const float cf = coef_of[(size_t)e][(size_t)r];
                    for (int q = 0; q < in_dim; ++q) dst[q] += cf * srcp[q];
                }
                if (obs) obs->on_expert(L, e, xc.data(), yc.data(), rows.data(), n, in_dim);
                free_bufs.push_back(b);
                ++st.expert_reads;
                st.bytes_read += rec;
            };
            while (proc < needed.size()) {
                while (next < needed.size() && !free_bufs.empty()) {
                    int b = free_bufs.back();
                    free_bufs.pop_back();
                    buf_of[next] = b;
                    IoRequest rq;
                    rq.file = file;
                    rq.offset = el.record_offset(needed[next]);
                    rq.len = rec;
                    rq.dst = bufs[(size_t)b].data();
                    rq.tag = (uint64_t)next;
                    io.submit(rq);
                    ++next;
                }
                if (!next_trunk.empty()) {
                    const double t_pre = now_sec();
                    sio.prefetch(bk_, next_trunk, L + 1);
                    st.ahead_seconds += now_sec() - t_pre;
                }
                IoCompletion comp[8];
                const double t_wait = now_sec();
                int nc = io.wait(comp, 8, 1);
                st.expert_wait_seconds += now_sec() - t_wait;
                HK_CHECK(nc > 0, "expert reads stalled in layer %d", L);
                for (int i = 0; i < nc; ++i) {
                    HK_CHECK(comp[i].error == 0, "reading an expert of layer %d failed: %s", L, io_error_text(comp[i].error).c_str());
                    HK_CHECK(comp[i].bytes == rec, "short expert read in layer %d (%lld of %lld bytes)", L, (long long)comp[i].bytes,
                             (long long)rec);
                    ready[(size_t)comp[i].tag] = 1;
                }
                while (proc < next && ready[proc]) apply_expert(proc++);
            }
            st.expert_seconds += now_sec() - t_exp;

            // ---- phase C: up-projection, shared experts, residual ------------------
            const double t_post = now_sec();
            for (const Chunk& ch : chunks) {
                const int T = ch.b - ch.a;
                const size_t r0 = (size_t)ch.row0;
                TensorRef h2(&bk_, T, d), res(&bk_, T, d), yl(&bk_, T, in_dim), x(&bk_, T, d);
                bk_.upload(h2, 0, T, H2.data() + r0 * d);
                bk_.upload(res, 0, T, RES.data() + r0 * d);
                bk_.upload(yl, 0, T, YLAT.data() + r0 * in_dim);
                if (obs) obs->on_chunk(ch.job, ch.a, ch.b);
                layer_post(bk_, c, w, h2, res, yl, x, hook);
                bk_.download(x, 0, T, X.data() + r0 * d);
            }
            st.post_seconds += now_sec() - t_post;
        }
        if (obs) {
            LayerStates ls;
            ls.rows = N;
            ls.d = d;
            ls.in_dim = in_dim;
            ls.k = k;
            ls.x = X.data();
            if (moe) {
                ls.res = RES.data();
                ls.xlat = XLAT.data();
                ls.ylat = YLAT.data();
                ls.expert = ridx.data();
                ls.weight = rw.data();
            }
            obs->on_layer_states(L, ls);
            obs->on_layer_end(L);
        }
        {
            // the rest of the layer's weights, here and not at the closing brace so that it is timed
            const double t_free = now_sec();
            ws.clear();
            st.free_seconds += now_sec() - t_free;
        }
    }

    // ---- head: final norm and logits, a few positions at a time -------------------
    if (opt_.hidden_io) {
        for (size_t j = 0; j < jobs.size(); ++j) {
            const int n = jobs[j]->end - jobs[j]->ckpt->pos;
            jobs[j]->hidden_out.assign(X.begin() + (std::ptrdiff_t)((size_t)base[j] * (size_t)d),
                                       X.begin() + (std::ptrdiff_t)((size_t)(base[j] + n) * (size_t)d));
        }
    } else {
        const double t_head = now_sec();
        WeightSet hs(&bk_);
        if (!opt_.keep_head) impl_->load_head(bk_, c, hs);
        HeadW hw = bind_head(c, opt_.keep_head ? impl_->kept_head(bk_, c) : hs);
        std::vector<float> lg;
        for (size_t j = 0; j < jobs.size(); ++j) {
            SeqJob& job = *jobs[j];
            const int p0 = job.ckpt->pos, n = job.end - p0;
            job.out.resize((size_t)n);
            if (opt_.keep_logits) job.logits.resize((size_t)n * (size_t)c.vocab);
            for (int a = 0; a < n; a += std::max(1, opt_.head_chunk)) {
                const int T = std::min(std::max(1, opt_.head_chunk), n - a);
                const size_t r0 = (size_t)(base[j] + a);
                TensorRef x(&bk_, T, d), xn(&bk_, T, d), out(&bk_, T, c.vocab);
                bk_.upload(x, 0, T, X.data() + r0 * d);
                std::vector<Tensor*> blocks;
                struct BlockGuard {
                    Backend& bk;
                    std::vector<Tensor*>& v;
                    ~BlockGuard() {
                        for (Tensor* t : v) bk.release(t);
                    }
                } guard{bk_, blocks};
                for (auto& hb : hblocks) {
                    Tensor* t = bk_.alloc(T, d);
                    blocks.push_back(t);
                    bk_.upload(t, 0, T, hb.data() + r0 * d);
                }
                head_norm(bk_, c, hw, x, blocks, xn);
                if (obs) obs->on_chunk((int)j, p0 + a, p0 + a + T);
                apply_lin(bk_, hw.lm_head, xn, out, hook);
                lg.resize((size_t)T * (size_t)c.vocab);
                bk_.download(out, 0, T, lg.data());
                for (int t = 0; t < T; ++t) {
                    const int p = p0 + a + t;
                    const int32_t next = p + 1 < (int)job.tokens->size() ? (*job.tokens)[(size_t)p + 1] : -1;
                    logits_stats(lg.data() + (size_t)t * c.vocab, c.vocab, opt_.topk, next, job.out[(size_t)(a + t)]);
                }
                if (opt_.keep_logits) memcpy(job.logits.data() + (size_t)a * c.vocab, lg.data(), lg.size() * 4);
            }
        }
        st.head_seconds = now_sec() - t_head;
    }

    // ---- commit the new checkpoints -----------------------------------------------
    for (size_t j = 0; j < jobs.size(); ++j)
        if (jobs[j]->save_at >= 0) *jobs[j]->ckpt = std::move(staged[j]);

    st.bytes_read += sio.bytes_read() - bytes0;
    st.ram_bytes = sio.bytes_from_ram() - ram0;
    st.ahead_bytes = sio.bytes_ahead() - ahead0;
    st.trunk_wait_seconds = sio.trunk_wait_seconds() - wait0;
    st.trunk_copy_seconds = sio.trunk_copy_seconds() - copy0;
    st.seconds = now_sec() - t_start;
    return st;
}

}  // namespace hk