File size: 7,308 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
#include "loop/draft_loop.h"

#include <algorithm>

#include "common/base.h"

namespace hk {
namespace {

// keeps real Kimi's hidden state after the layers the drafter reads, for every row of a sweep
struct TapObserver : SweepObserver {
    const std::vector<int>& taps;
    std::vector<std::vector<float>> rows;   // per tap: [sweep rows, hidden]
    explicit TapObserver(const std::vector<int>& t) : taps(t), rows(t.size()) {}
    void on_layer_states(int layer, const LayerStates& s) override {
        for (size_t i = 0; i < taps.size(); ++i)
            if (taps[i] == layer) rows[i].assign(s.x, s.x + (size_t)s.rows * (size_t)s.d);
    }
};

bool is_stop(const std::vector<int32_t>& stop_ids, int32_t t) { return std::find(stop_ids.begin(), stop_ids.end(), t) != stop_ids.end(); }

}  // namespace

int best_check_len(const std::vector<float>& conf, int limit, double extra) {
    int best = 0;
    double best_rate = 1.0, expect = 0.0, all = 1.0;   // n = 0: one token for one unit of cost
    for (int n = 1; n <= limit; ++n) {
        all *= (size_t)(n - 1) < conf.size() ? std::min(1.0, std::max(0.0, (double)conf[(size_t)(n - 1)])) : 0.8;
        expect += all;   // the chance that the first n are all accepted
        const double rate = (1.0 + expect) / (1.0 + extra * n);
        if (rate > best_rate) {
            best_rate = rate;
            best = n;
        }
    }
    return best;
}

DraftSession::DraftSession(Reader& reader, DSpark& drafter) : reader_(reader), drafter_(drafter) { ckpt_.reset(reader.config()); }

void DraftSession::reset() {
    seq_.clear();
    ckpt_.reset(reader_.config());
    drafter_.truncate(0);
}

double DraftSession::extra_cost(double start) const {
    // a line through the timed sweeps: seconds = a + b * n (needs sweeps of at least two lengths)
    double extra = start;
    if (timed_ >= 6 && max_n_ > min_n_) {
        const double var = sum_nn_ - sum_n_ * sum_n_ / timed_;
        const double b = var > 0 ? (sum_nt_ - sum_n_ * sum_t_ / timed_) / var : 0.0;
        const double a = (sum_t_ - b * sum_n_) / timed_;
        // the first sweeps weigh little against the starting value, a long answer decides by itself
        if (a > 0 && b > 0) extra = (start * 8 + (b / a) * timed_) / (8 + timed_);
    }
    return std::min(1.0, std::max(0.01, extra));
}

DayResult DraftSession::generate(const std::vector<int32_t>& prompt, const DayOptions& opt, const DayCallbacks& cb) {
    const double t_start = now_sec();
    DayResult res;
    seq_.insert(seq_.end(), prompt.begin(), prompt.end());
    HK_CHECK(!seq_.empty(), "nothing to continue: the conversation is empty");
    HK_CHECK(ckpt_.pos == drafter_.context() && ckpt_.pos <= (int)seq_.size(), "internal: real Kimi is at position %d, the drafter at %d",
             ckpt_.pos, drafter_.context());
    const double start_extra = opt.extra_cost > 0 ? opt.extra_cost : 0.085;

    while ((int)res.tokens.size() < opt.max_new && !res.stopped && (int)res.rounds.size() < opt.max_rounds) {
        const int L = (int)seq_.size(), pos0 = ckpt_.pos;
        const int left = opt.max_new - (int)res.tokens.size();
        RoundInfo round;

        // ---- draft: only when the one position real Kimi has not processed is the last token ----
        DraftBlock block;
        int n = 0;
        if (pos0 == L - 1 && left > 1) {
            const double t0 = now_sec();
            const int limit = std::min(drafter_.drafted(), left - 1);   // the sweep adds one token of its own
            drafter_.draft(seq_.back(), limit, block);
            n = opt.draft_len > 0 ? std::min(opt.draft_len, (int)block.tokens.size())
                                  : best_check_len(block.conf, (int)block.tokens.size(), extra_cost(start_extra));
            round.draft_seconds = now_sec() - t0;
            if (cb.on_draft && n > 0) cb.on_draft(block.tokens.data(), n);
        }

        // ---- check: real Kimi over what it has not processed and the n drafted tokens ----------
        std::vector<int32_t> text(seq_);
        text.insert(text.end(), block.tokens.begin(), block.tokens.begin() + n);
        SeqJob job;
        job.tokens = &text;
        job.ckpt = &ckpt_;
        job.end = L + n;
        job.save_at = L + n;
        job.keep_tail = n > 0;
        TapObserver taps(drafter_.taps());
        SweepStats st = reader_.sweep(job, &taps);
        round.sweep_seconds = st.seconds;
        round.sweep_bytes = st.bytes_read;
        if (pos0 == L - 1) {
            sum_n_ += n;
            sum_t_ += st.seconds;
            sum_nn_ += (double)n * n;
            sum_nt_ += (double)n * st.seconds;
            ++timed_;
            min_n_ = std::min(min_n_, n);
            max_n_ = std::max(max_n_, n);
        }

        // Row L-1-pos0 is the last token: what real Kimi puts first there is the token for position L.
        // A drafted token that is that token is kept, and its own row decides the next one.
        const size_t base = (size_t)(L - 1 - pos0);
        int a = 0;
        for (; a < n; ++a) {
            const PosResult& r = job.out[base + (size_t)a];
            if (r.top_id.empty() || r.top_id[0] != block.tokens[(size_t)a]) break;
        }
        std::vector<int32_t> fresh(block.tokens.begin(), block.tokens.begin() + a);
        HK_CHECK(!job.out[base + (size_t)a].top_id.empty(), "internal: the sweep returned no prediction");
        fresh.push_back(job.out[base + (size_t)a].top_id[0]);   // real Kimi's own token after the kept ones
        // the answer ends at the first stop token, or when it is long enough
        int m = std::min((int)fresh.size(), left);
        for (int i = 0; i < m; ++i)
            if (is_stop(opt.stop_ids, fresh[(size_t)i])) {
                m = i + 1;
                res.stopped = true;
                break;
            }
        fresh.resize((size_t)m);

        // Real Kimi's state and the drafter's context go to just before the new last token. These
        // positions were swept with the tokens that stand, so nothing is swept again.
        const int keep = L + m - 1;
        if (job.keep_tail) ckpt_.rewind(keep);
        std::vector<const float*> states;
        for (const std::vector<float>& v : taps.rows) {
            HK_CHECK(v.size() >= (size_t)(keep - pos0) * (size_t)reader_.config().hidden, "internal: a layer the drafter reads was not swept");
            states.push_back(v.data());
        }
        drafter_.extend(states, keep - pos0);

        seq_.insert(seq_.end(), fresh.begin(), fresh.end());
        res.tokens.insert(res.tokens.end(), fresh.begin(), fresh.end());
        if (cb.on_approved) cb.on_approved(fresh.data(), m);

        round.drafted = n;
        round.accepted = a;
        round.fixed = a < n;
        res.fixes += round.fixed ? 1 : 0;
        res.draft_seconds += round.draft_seconds;
        res.sweep_seconds += round.sweep_seconds;
        res.sweep_bytes += round.sweep_bytes;
        res.rounds.push_back(round);
        drafted_ += n;
        accepted_ += a;
        if (record) {
            Drafted d;
            d.anchor_pos = L - 1;
            d.block = std::move(block);
            d.checked = n;
            d.kept = a;
            record->push_back(std::move(d));
        }
    }
    res.seconds = now_sec() - t_start;
    return res;
}

}  // namespace hk