File size: 9,437 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
#include "format/store.h"

#include <algorithm>
#include <cstring>
#include <filesystem>
#include <fstream>

#include "common/base.h"
#include "common/numeric.h"

namespace hk {

ExpertViews expert_views(const ExpertLayer& el, const uint8_t* rec, int nplanes) {
    HK_CHECK(nplanes >= 1 && nplanes <= 4, "nplanes must be 1..4");
    ExpertViews v;
    const int rows[3] = {el.inter, el.inter, el.in_dim};
    const int cols[3] = {el.in_dim, el.in_dim, el.inter};
    int64_t soff = 0, poff = 0;
    for (int m = 0; m < 3; ++m) {
        PlanesDesc& d = v.desc[m];
        d.rows = rows[m];
        d.cols = cols[m];
        d.nplanes = nplanes;
        d.group = 32;
        d.scale = ScaleKind::E8M0;
        for (int i = 0; i < 8; ++i) d.lut[i] = el.lut[nplanes - 1][i];
        v.view[m].scales = rec + soff;
        for (int p = 0; p < nplanes; ++p) v.view[m].planes[p] = rec + el.scale_bytes() + (int64_t)p * el.plane_bytes() + poff;
        soff += d.scale_bytes();
        poff += d.plane_bytes();
    }
    return v;
}

// Header layout (little endian):
//   0  "HKX1"      4  version (1)   8  layer        12 n_experts
//   16 in_dim      20 inter         24 group (32)   28 nplanes (4)
//   32 header_bytes(u64)  40 scale_bytes(u64)  48 plane_bytes(u64)  56 record_bytes(u64)
//   64 lut[4][8] as float32          192 requantized (u32)
void hkx_write_header(const ExpertLayer& el, uint8_t* h) {
    memset(h, 0, (size_t)kHkxHeaderBytes);
    memcpy(h, "HKX1", 4);
    store_le32(h + 4, 1);
    store_le32(h + 8, (uint32_t)el.layer);
    store_le32(h + 12, (uint32_t)el.n_experts);
    store_le32(h + 16, (uint32_t)el.in_dim);
    store_le32(h + 20, (uint32_t)el.inter);
    store_le32(h + 24, 32);
    store_le32(h + 28, 4);
    store_le64(h + 32, (uint64_t)kHkxHeaderBytes);
    store_le64(h + 40, (uint64_t)el.scale_bytes());
    store_le64(h + 48, (uint64_t)el.plane_bytes());
    store_le64(h + 56, (uint64_t)el.record_bytes());
    for (int k = 0; k < 4; ++k)
        for (int i = 0; i < 8; ++i) {
            uint32_t u;
            memcpy(&u, &el.lut[k][i], 4);
            store_le32(h + 64 + 4 * (k * 8 + i), u);
        }
    store_le32(h + 192, el.requantized ? 1u : 0u);
}

void hkx_check_header(const ExpertLayer& el, const uint8_t* h) {
    HK_CHECK(memcmp(h, "HKX1", 4) == 0, "%s is not an expert file (bad magic)", el.file.c_str());
    HK_CHECK(load_le32(h + 4) == 1, "%s: unsupported expert file version %u", el.file.c_str(), load_le32(h + 4));
    HK_CHECK((int)load_le32(h + 8) == el.layer && (int)load_le32(h + 12) == el.n_experts &&
                 (int)load_le32(h + 16) == el.in_dim && (int)load_le32(h + 20) == el.inter &&
                 (int64_t)load_le64(h + 56) == el.record_bytes(),
             "%s: header does not match the manifest (was the store edited by hand?)", el.file.c_str());
}

static Json shape_json(const std::vector<int64_t>& shape) {
    Json a = Json::array();
    for (int64_t d : shape) a.push(Json(d));
    return a;
}

Json Store::make_manifest(const Json& original_config, const std::vector<TrunkEntry>& trunk,
                          const std::vector<ExpertLayer>& experts, const std::string& source) {
    Json m = Json::object();
    m.set("format", "hkimi-store");
    m.set("version", 1);
    m.set("source", source);
    m.set("config", original_config);
    Json tr = Json::object();
    tr.set("file", "trunk.bin");
    Json list = Json::array();
    for (const auto& e : trunk) {
        Json j = Json::object();
        j.set("name", e.name);
        j.set("dtype", e.dtype);
        j.set("shape", shape_json(e.shape));
        j.set("offset", Json(e.offset));
        j.set("nbytes", Json(e.nbytes));
        list.push(std::move(j));
    }
    tr.set("tensors", std::move(list));
    m.set("trunk", std::move(tr));
    Json ex = Json::array();
    for (const auto& el : experts) {
        Json j = Json::object();
        j.set("layer", el.layer);
        j.set("file", el.file);
        j.set("n_experts", el.n_experts);
        j.set("in_dim", el.in_dim);
        j.set("inter", el.inter);
        j.set("requantized", el.requantized);
        j.set("record_bytes", Json(el.record_bytes()));
        Json luts = Json::array();
        for (int k = 0; k < 4; ++k) {
            Json row = Json::array();
            for (int i = 0; i < 8; ++i) row.push(Json((double)el.lut[k][i]));
            luts.push(std::move(row));
        }
        j.set("lut", std::move(luts));
        ex.push(std::move(j));
    }
    m.set("experts", std::move(ex));
    return m;
}

Store Store::open(const std::string& dir) {
    Store s;
    s.dir_ = dir;
    std::string mp = path_join(dir, "manifest.json");
    HK_CHECK(file_exists(mp), "%s is not a store (no manifest.json). Create one with: hkimi convert <checkpoint> %s",
             dir.c_str(), dir.c_str());
    s.manifest_ = Json::parse_file(mp);
    HK_CHECK(s.manifest_.get_str("format", "") == "hkimi-store", "%s: not an hkimi store manifest", mp.c_str());
    HK_CHECK(s.manifest_.get_int("version", 0) == 1, "%s: store version %lld is not supported by this build", mp.c_str(),
             (long long)s.manifest_.get_int("version", 0));
    s.config_ = ModelConfig::from_json(s.manifest_.at("config"));
    for (const Json& j : s.manifest_.at("trunk").at("tensors").elems()) {
        TrunkEntry e;
        e.name = j.at("name").as_str();
        e.dtype = j.at("dtype").as_str();
        for (const Json& d : j.at("shape").elems()) e.shape.push_back(d.as_int());
        e.offset = j.at("offset").as_int();
        e.nbytes = j.at("nbytes").as_int();
        s.by_name_[e.name] = (int)s.trunk_.size();
        s.trunk_.push_back(std::move(e));
    }
    s.layer_slot_.assign((size_t)s.config_.layers, -1);
    for (const Json& j : s.manifest_.at("experts").elems()) {
        ExpertLayer el;
        el.layer = (int)j.at("layer").as_int();
        el.file = j.at("file").as_str();
        el.n_experts = (int)j.at("n_experts").as_int();
        el.in_dim = (int)j.at("in_dim").as_int();
        el.inter = (int)j.at("inter").as_int();
        el.requantized = j.get_bool("requantized", false);
        const Json& luts = j.at("lut");
        for (int k = 0; k < 4; ++k)
            for (int i = 0; i < 8; ++i) el.lut[k][i] = (float)luts[(size_t)k][(size_t)i].as_num();
        HK_CHECK(el.layer >= 0 && el.layer < s.config_.layers, "manifest lists experts for layer %d", el.layer);
        HK_CHECK(j.at("record_bytes").as_int() == el.record_bytes(), "manifest record size mismatch for layer %d", el.layer);
        s.layer_slot_[(size_t)el.layer] = (int)s.experts_.size();
        s.experts_.push_back(el);
    }
    return s;
}

const TrunkEntry* Store::find(const std::string& name) const {
    auto it = by_name_.find(name);
    return it == by_name_.end() ? nullptr : &trunk_[(size_t)it->second];
}
const TrunkEntry& Store::get(const std::string& name) const {
    const TrunkEntry* e = find(name);
    HK_CHECK(e != nullptr, "tensor %s is not in the store", name.c_str());
    return *e;
}
const ExpertLayer& Store::experts(int layer) const {
    HK_CHECK(has_experts(layer), "the store has no experts for layer %d (partial conversion?)", layer);
    return experts_[(size_t)layer_slot_[(size_t)layer]];
}

OutFile::~OutFile() {
    try {
        close();
    } catch (...) {
        // a destructor must not throw; callers that care call close()
    }
}

void OutFile::open(const std::string& path, bool truncate) {
    close();
    path_ = path;
    auto* f = new std::fstream();
    auto mode = std::ios::binary | std::ios::out | std::ios::in;
    if (truncate || !file_exists(path)) mode |= std::ios::trunc;
    f->open(std::filesystem::u8path(path), mode);
    if (!f->good()) {
        delete f;
        HK_FAIL("cannot open %s for writing", path.c_str());
    }
    f->seekp(0, std::ios::end);
    pos_ = (int64_t)f->tellp();
    f_ = f;
}

// A tensor can be over 2 GB (embedding and output head are 2.35 GB each). Written in
// pieces, so nothing depends on how a runtime treats one write of that size.
static void write_pieces(std::fstream& f, const void* data, int64_t n) {
    const int64_t kPiece = (int64_t)64 << 20;
    const char* p = (const char*)data;
    for (int64_t done = 0; done < n; done += kPiece) f.write(p + done, (std::streamsize)std::min(kPiece, n - done));
}

void OutFile::write(const void* data, int64_t n) {
    auto* f = (std::fstream*)f_;
    HK_CHECK(f != nullptr, "write on a closed file");
    write_pieces(*f, data, n);
    HK_CHECK(f->good(), "write failed on %s (disk full?)", path_.c_str());
    pos_ += n;
}

void OutFile::pad_to(int64_t align) {
    static const char zeros[4096] = {0};
    int64_t pad = align_up(pos_, align) - pos_;
    while (pad > 0) {
        int64_t n = pad < 4096 ? pad : 4096;
        write(zeros, n);
        pad -= n;
    }
}

void OutFile::write_at(int64_t offset, const void* data, int64_t n) {
    auto* f = (std::fstream*)f_;
    HK_CHECK(f != nullptr, "write on a closed file");
    f->seekp((std::streamoff)offset, std::ios::beg);
    write_pieces(*f, data, n);
    f->seekp(0, std::ios::end);
    HK_CHECK(f->good(), "positioned write failed on %s", path_.c_str());
}

void OutFile::close() {
    auto* f = (std::fstream*)f_;
    if (!f) return;
    f->flush();
    bool ok = f->good();
    f->close();
    delete f;
    f_ = nullptr;
    HK_CHECK(ok, "closing %s failed (disk full?)", path_.c_str());
}

}  // namespace hk