hkimi / src /convert /convert.cpp
Ozomozyan's picture
hkimi 0.1.0
68888be verified
Raw History Blame Contribute Delete
25.6 kB
#include "convert/convert.h"
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <unordered_map>
#include <unordered_set>
#include "common/base.h"
#include "common/numeric.h"
#include "common/threads.h"
#include "format/planes.h"
#include "format/safetensors.h"
#include "format/store.h"
#include "io/file_io.h"
#include "io/os_info.h"
#include "model/config.h"
#include "model/weights.h"
namespace hk {
namespace {
namespace fs = std::filesystem;
// Reads tensors from the source shards and counts what each shard still owes, so a
// shard can be deleted once it is drained. Its reader is closed first: on Linux a
// deleted file keeps its space while someone holds it open, Windows refuses the delete.
class Source {
public:
Source(const StModel& m, bool delete_source) : m_(m), delete_(delete_source) {
readers_.resize(m.shards().size());
pending_.assign(m.shards().size(), 0);
}
void need(const StTensor& t) { ++pending_[(size_t)t.shard]; }
// per shard: tensors still to read
const std::vector<int>& pending() const { return pending_; }
void read(const StTensor& t, uint8_t* dst) {
Reader& r = reader((size_t)t.shard);
r.io->read_range(r.file, t.offset, t.nbytes, dst);
}
// call once a needed tensor is in the store
void done(const StTensor& t) {
const size_t s = (size_t)t.shard;
HK_CHECK(pending_[s] > 0, "internal: shard accounting went negative for %s", t.name.c_str());
if (--pending_[s] > 0) return;
close(s); // nothing more is read from this shard
if (!delete_) return;
const StShard& sh = m_.shards()[s];
HK_CHECK(!file_is_open_here(sh.path), "internal: %s is still open, deleting it now would not free its space", sh.path.c_str());
// record first, delete second: a shard listed but still present costs nothing on a rerun
std::string ledger = path_join(m_.dir(), ".hkimi-reclaimed");
std::string prev = file_exists(ledger) ? read_text_file(ledger) : "";
write_text_file(ledger, prev + sh.file + "\n");
std::error_code ec;
fs::remove(fs::u8path(sh.path), ec);
if (ec) {
HK_WARN("could not delete %s: %s", sh.path.c_str(), ec.message().c_str());
} else {
++deleted;
deleted_bytes += sh.size;
}
}
int deleted = 0;
int64_t deleted_bytes = 0;
private:
struct Reader {
std::unique_ptr<IoEngine> io; // null while the shard is closed
int file = -1;
uint64_t used = 0;
};
// Only a few readers stay open (each costs threads or a kernel queue); the one unused for longest goes.
static constexpr int kMaxOpen = 4;
Reader& reader(size_t s) {
Reader& r = readers_[s];
if (!r.io) {
if (open_ >= kMaxOpen) {
size_t oldest = s;
for (size_t i = 0; i < readers_.size(); ++i)
if (readers_[i].io && (oldest == s || readers_[i].used < readers_[oldest].used)) oldest = i;
close(oldest);
}
r.io = IoEngine::create(io_opt_);
// "auto" probes once, later readers take what it found
const std::string found = r.io->name();
io_opt_.engine = found == "io_uring" ? "uring" : found;
r.file = r.io->open(m_.shards()[s].path);
++open_;
}
r.used = ++clock_;
return r;
}
void close(size_t s) {
Reader& r = readers_[s];
if (!r.io) return;
r.io.reset(); // the engine closes its file when it goes
r.file = -1;
--open_;
}
const StModel& m_;
bool delete_;
IoOptions io_opt_;
std::vector<Reader> readers_;
std::vector<int> pending_;
int open_ = 0;
uint64_t clock_ = 0;
};
struct ExpertSrc {
// per matrix (gate, up, down): packed + scale tensors (MXFP4) or one dense tensor (BF16 / F32)
const StTensor* packed[3] = {nullptr, nullptr, nullptr};
const StTensor* scale[3] = {nullptr, nullptr, nullptr};
const StTensor* dense[3] = {nullptr, nullptr, nullptr};
};
bool find_expert(const StModel& m, const ModelConfig& c, int L, int e, ExpertSrc& out, bool* mxfp4) {
bool any_packed = false, any_dense = false;
for (int w = 0; w < 3; ++w) {
std::string base = c.n_expert(L, e, w);
out.packed[w] = m.find(base + ".weight_packed");
out.scale[w] = m.find(base + ".weight_scale");
out.dense[w] = m.find(base + ".weight");
if (out.packed[w] && out.scale[w]) any_packed = true;
else if (out.dense[w]) any_dense = true;
else return false;
}
HK_CHECK(any_packed != any_dense, "layer %d expert %d mixes packed and dense matrices", L, e);
*mxfp4 = any_packed;
return true;
}
// the source tensors of one expert, in the order the converter finishes with them
template <class F>
void each_source(bool mxfp4, const ExpertSrc& es, F&& f) {
for (int w = 0; w < 3; ++w) {
if (mxfp4) {
f(*es.packed[w]);
f(*es.scale[w]);
} else {
f(*es.dense[w]);
}
}
}
void check_shape(const StTensor& t, int64_t rows, int64_t cols, const char* dtype) {
HK_CHECK(t.shape.size() == 2 && t.shape[0] == rows && t.shape[1] == cols && t.dtype == dtype,
"%s: expected %s [%lld, %lld], the checkpoint has %s with %zu dims (first %lld)", t.name.c_str(), dtype,
(long long)rows, (long long)cols, t.dtype.c_str(), t.shape.size(), t.shape.empty() ? 0LL : (long long)t.shape[0]);
}
} // namespace
ConvertReport convert_checkpoint(const ConvertOptions& opt) {
const double t0 = now_sec();
ConvertReport rep;
StModel src(opt.src);
HK_CHECK(src.config().is_obj(), "%s has no config.json", opt.src.c_str());
ModelConfig cfg = ModelConfig::from_json(src.config());
HK_INFO("source: %s", cfg.summary().c_str());
// refuse layouts where deleting source shards could eat the output
{
std::error_code ec;
fs::path a = fs::weakly_canonical(fs::u8path(opt.src), ec), b = fs::weakly_canonical(fs::u8path(opt.dst), ec);
HK_CHECK(a != b, "source and destination are the same directory");
if (opt.delete_source) {
auto rel = fs::relative(b, a, ec).u8string();
HK_CHECK(ec || rel.empty() || rel.rfind("..", 0) == 0, "--delete-source refuses to run with the store inside the checkpoint directory");
}
}
make_dirs(opt.dst);
make_dirs(path_join(opt.dst, "experts"));
std::vector<int> layers = opt.layers;
const bool partial = !layers.empty();
if (!partial)
for (int L = 0; L < cfg.layers; ++L) layers.push_back(L);
for (int L : layers) HK_CHECK(L >= 0 && L < cfg.layers, "layer %d does not exist (the model has %d)", L, cfg.layers);
// ---- plan: which trunk tensors, which experts --------------------------
std::vector<const StTensor*> trunk_src;
std::unordered_set<std::string> consumed;
auto want_trunk = [&](const std::string& name, bool optional) {
const StTensor* t = src.find(name);
if (!t || !t->available()) {
HK_CHECK(optional, "tensor %s is %s. %s", name.c_str(), t ? "in a shard that is not on disk" : "not in the checkpoint",
t ? "Download that shard, or convert only the layers you have with --layers."
: "The checkpoint layout differs from what this build expects (run `hkimi inspect`).");
HK_WARN("skipping %s (not available)", name.c_str());
return;
}
trunk_src.push_back(t);
consumed.insert(name);
};
const bool head_optional = partial || opt.allow_missing_head;
want_trunk(cfg.n_embed(), head_optional);
for (int L : layers)
for (const TensorNeed& n : layer_tensors(cfg, L)) want_trunk(n.name, false);
for (const TensorNeed& n : head_tensors(cfg)) want_trunk(n.name, head_optional);
struct LayerPlan {
int layer;
bool mxfp4;
std::vector<ExpertSrc> experts;
};
std::vector<LayerPlan> plans;
for (int L : layers) {
if (!cfg.is_moe(L)) continue;
LayerPlan lp;
lp.layer = L;
lp.mxfp4 = false;
lp.experts.resize((size_t)cfg.n_experts);
for (int e = 0; e < cfg.n_experts; ++e) {
bool mx = false;
HK_CHECK(find_expert(src, cfg, L, e, lp.experts[(size_t)e], &mx),
"layer %d expert %d: its matrices are not in the checkpoint under %s.{weight_packed,weight_scale} or .weight",
L, e, cfg.n_expert(L, e, 0).c_str());
HK_CHECK(e == 0 || mx == lp.mxfp4, "layer %d mixes MXFP4 and dense experts", L);
lp.mxfp4 = mx;
for (int w = 0; w < 3; ++w) {
const ExpertSrc& es = lp.experts[(size_t)e];
for (const StTensor* t : {es.packed[w], es.scale[w], es.dense[w]}) {
if (!t) continue;
if (mx == (t == es.dense[w])) continue; // the other representation, unused
HK_CHECK(t->available(), "%s is in a shard that is not on disk", t->name.c_str());
consumed.insert(t->name);
}
}
}
HK_CHECK(lp.mxfp4 || opt.requantize,
"layer %d has dense (%s) experts. Pass --requantize to store them as MXFP4 bit planes; "
"this quantizes them, so the stored model is no longer bit-identical to the checkpoint.",
L, lp.experts[0].dense[0]->dtype.c_str());
plans.push_back(std::move(lp));
}
// anything in the checkpoint we do not use?
{
int shown = 0;
for (const StTensor& t : src.tensors()) {
if (consumed.count(t.name) || tensor_is_ignorable(cfg, t.name)) continue;
if (partial) {
// in a partial conversion the skipped layers' tensors are expected
if (t.name.find("model.layers.") != std::string::npos || t.name == cfg.n_embed() || t.name == cfg.n_lm_head() ||
t.name.find("model.norm") != std::string::npos || t.name.find("output_attn_res") != std::string::npos)
continue;
}
++rep.unused_tensors;
if (shown++ < 12) HK_WARN("checkpoint tensor not used by the engine: %s %s", t.name.c_str(), t.dtype.c_str());
}
if (rep.unused_tensors > 12) HK_WARN("... and %d more unused tensors", rep.unused_tensors - 12);
HK_CHECK(!(opt.strict && rep.unused_tensors > 0),
"%d checkpoint tensors are unknown to the engine (--strict). The forward pass may be missing a component.",
rep.unused_tensors);
}
Source source(src, opt.delete_source);
for (const StTensor* t : trunk_src) source.need(*t);
for (const LayerPlan& lp : plans)
for (const ExpertSrc& es : lp.experts) each_source(lp.mxfp4, es, [&](const StTensor& t) { source.need(t); });
// files an earlier run left under the same names: they get replaced, so their room counts as free
std::vector<fs::path> stale;
int64_t stale_bytes = 0;
{
std::vector<std::string> names = {"manifest.json", "trunk.bin"};
for (const LayerPlan& lp : plans) names.push_back(strfmt("experts/L%04d.hkx", lp.layer));
for (const std::string& rel : names) {
const fs::path f = fs::u8path(path_join(opt.dst, rel));
std::error_code ec;
const auto size = fs::file_size(f, ec);
if (ec) continue; // not there
stale.push_back(f);
stale_bytes += (int64_t)size;
}
}
// ---- room on the disk --------------------------------------------------------
// The same walk as the run below. Refusing here costs a second, running out of disk at layer 13 costs hours.
{
ExpertLayer geo;
geo.n_experts = cfg.n_experts;
geo.in_dim = cfg.expert_in();
geo.inter = cfg.moe_inter;
const int64_t rec = geo.record_bytes();
std::vector<int64_t> gives(src.shards().size(), 0); // what deleting each shard gives back
int links = 0;
for (size_t i = 0; i < src.shards().size(); ++i) {
const StShard& sh = src.shards()[i];
if (!sh.present) continue;
std::error_code ec;
if (fs::is_symlink(fs::u8path(sh.path), ec)) ++links; // deleting a link frees nothing
else gives[i] = sh.size;
}
std::vector<int> left = source.pending();
int64_t written = 0, freed = 0, peak = 0;
auto wrote = [&](int64_t n) {
written += n;
peak = std::max(peak, written - freed);
};
auto used = [&](const StTensor& t) {
if (--left[(size_t)t.shard] == 0) freed += gives[(size_t)t.shard];
};
for (const StTensor* t : trunk_src) {
wrote(align_up(t->nbytes));
used(*t);
}
for (const LayerPlan& lp : plans) {
wrote(kHkxHeaderBytes);
for (const ExpertSrc& es : lp.experts) {
wrote(rec);
each_source(lp.mxfp4, es, used);
}
}
const int64_t total = written;
const bool same = same_volume(opt.src, opt.dst);
const bool reclaim = opt.delete_source && same;
const int64_t need = reclaim ? peak : total;
int64_t have = disk_free_bytes(opt.dst);
if (const char* fake = std::getenv("HKIMI_TEST_DISK_FREE")) have = (int64_t)strtoll(fake, nullptr, 10); // for the tests
if (have >= 0) have += stale_bytes;
const std::string have_text = have >= 0 ? human_bytes((double)have) : "an unknown amount";
if (reclaim)
HK_INFO("disk: the store takes %s. Shards are deleted as they are converted, so at most %s of free space is "
"needed at one time; %s is free",
human_bytes((double)total).c_str(), human_bytes((double)need).c_str(), have_text.c_str());
else
HK_INFO("disk: the store takes %s; %s is free", human_bytes((double)total).c_str(), have_text.c_str());
if (opt.delete_source && !same)
HK_WARN("the store is on another disk than the checkpoint: deleting shards makes no room for it");
if (opt.delete_source && links)
HK_WARN("%d shard(s) are symbolic links (a Hugging Face cache folder?): deleting a link does not free the file behind it", links);
// a little air on top: file-system bookkeeping, other writers
auto with_air = [](int64_t n) { return n + n / 100 + ((int64_t)16 << 20); };
if (opt.space_check && have >= 0 && have < with_air(need)) {
std::string hint;
if (!opt.delete_source && same && with_air(peak) <= have)
hint = strfmt(" With --delete-source each shard is deleted once it is converted, and %s would be enough.",
human_bytes((double)with_air(peak)).c_str());
HK_FAIL("not enough disk space: the conversion needs %s free on the disk of %s, and %s is free (%s short).%s "
"Nothing was written. (--no-space-check runs anyway.)",
human_bytes((double)with_air(need)).c_str(), opt.dst.c_str(), have_text.c_str(),
human_bytes((double)(with_air(need) - have)).c_str(), hint.c_str());
}
}
// manifest.json is written last and marks a finished store, so the old files go now:
// a run that fails later must not pass for one
if (!stale.empty()) {
for (const fs::path& f : stale) {
std::error_code ec;
fs::remove(f, ec);
}
HK_INFO("cleared %d file(s) of an earlier conversion in %s (%s)", (int)stale.size(), opt.dst.c_str(),
human_bytes((double)stale_bytes).c_str());
}
// with --delete-source the free space should stay about level from layer to layer
auto room = [&]() -> std::string {
if (!opt.delete_source) return "";
const int64_t free_now = disk_free_bytes(opt.dst);
return strfmt(" | %d shard(s) deleted so far, %s free", source.deleted,
free_now >= 0 ? human_bytes((double)free_now).c_str() : "unknown space");
};
// ---- trunk ---------------------------------------------------------------
std::vector<TrunkEntry> trunk;
{
OutFile out;
out.open(path_join(opt.dst, "trunk.bin"));
std::vector<uint8_t> buf;
for (const StTensor* t : trunk_src) {
HK_CHECK(t->dtype == "BF16" || t->dtype == "F32" || t->dtype == "F16", "trunk tensor %s has unsupported dtype %s",
t->name.c_str(), t->dtype.c_str());
out.pad_to(kIoAlign);
TrunkEntry e;
e.name = t->name;
e.dtype = t->dtype;
e.shape = t->shape;
e.offset = out.tell();
e.nbytes = t->nbytes;
buf.resize((size_t)t->nbytes);
source.read(*t, buf.data());
out.write(buf.data(), t->nbytes);
source.done(*t);
trunk.push_back(std::move(e));
rep.trunk_bytes += t->nbytes;
}
out.pad_to(kIoAlign);
out.close();
rep.trunk_tensors = (int)trunk.size();
HK_INFO("trunk: %d tensors, %s%s", rep.trunk_tensors, human_bytes((double)rep.trunk_bytes).c_str(), room().c_str());
}
// ---- experts ---------------------------------------------------------------
std::vector<ExpertLayer> expert_layers;
const int in_dim = cfg.expert_in(), inter = cfg.moe_inter;
for (const LayerPlan& lp : plans) {
const double t_layer = now_sec();
ExpertLayer el;
el.layer = lp.layer;
el.file = strfmt("experts/L%04d.hkx", lp.layer);
el.n_experts = cfg.n_experts;
el.in_dim = in_dim;
el.inter = inter;
el.requantized = !lp.mxfp4;
HK_CHECK(in_dim % 32 == 0 && inter % 32 == 0, "expert dims %d x %d are not multiples of 32 (MXFP4 groups)", inter, in_dim);
const int rows[3] = {inter, inter, in_dim};
const int cols[3] = {in_dim, in_dim, inter};
OutFile out;
out.open(path_join(opt.dst, el.file));
std::vector<uint8_t> header((size_t)kHkxHeaderBytes, 0);
out.write(header.data(), kHkxHeaderBytes); // rewritten at the end, once the tables are known
const int64_t rec_bytes = el.record_bytes();
double hist[8] = {0, 0, 0, 0, 0, 0, 0, 0};
const int B = std::max(1, opt.batch);
struct Work {
std::vector<uint8_t> packed[3], scales[3], dense[3], record;
double hist[8];
};
std::vector<Work> work((size_t)B);
for (int e0 = 0; e0 < cfg.n_experts; e0 += B) {
const int nb = std::min(B, cfg.n_experts - e0);
// reads are single-threaded, the conversion below is parallel
for (int i = 0; i < nb; ++i) {
const ExpertSrc& es = lp.experts[(size_t)(e0 + i)];
Work& wk = work[(size_t)i];
for (int w = 0; w < 3; ++w) {
if (lp.mxfp4) {
check_shape(*es.packed[w], rows[w], cols[w] / 2, "U8");
check_shape(*es.scale[w], rows[w], cols[w] / 32, es.scale[w]->dtype == "F8_E8M0" ? "F8_E8M0" : "U8");
wk.packed[w].resize((size_t)es.packed[w]->nbytes);
wk.scales[w].resize((size_t)es.scale[w]->nbytes);
source.read(*es.packed[w], wk.packed[w].data());
source.read(*es.scale[w], wk.scales[w].data());
} else {
HK_CHECK(es.dense[w]->shape.size() == 2 && es.dense[w]->shape[0] == rows[w] && es.dense[w]->shape[1] == cols[w],
"%s: unexpected shape for an expert matrix", es.dense[w]->name.c_str());
wk.dense[w].resize((size_t)es.dense[w]->nbytes);
source.read(*es.dense[w], wk.dense[w].data());
}
}
}
parallel_for(nb, 1, [&](int64_t b, int64_t e) {
for (int64_t i = b; i < e; ++i) {
Work& wk = work[(size_t)i];
const ExpertSrc& es = lp.experts[(size_t)(e0 + i)];
for (int c = 0; c < 8; ++c) wk.hist[c] = 0;
wk.record.assign((size_t)rec_bytes, 0);
uint8_t* rec = wk.record.data();
int64_t soff = 0, poff = 0;
std::vector<float> rowf;
for (int w = 0; w < 3; ++w) {
const int64_t nsc = (int64_t)rows[w] * (cols[w] / 32);
const int64_t npl = (int64_t)rows[w] * (cols[w] / 8);
if (!lp.mxfp4) {
// dense expert: quantize each row to MXFP4 first
wk.packed[w].assign((size_t)rows[w] * (size_t)(cols[w] / 2), 0);
wk.scales[w].assign((size_t)nsc, 0);
rowf.resize((size_t)cols[w]);
const int es_bytes = dtype_size(es.dense[w]->dtype);
for (int r = 0; r < rows[w]; ++r) {
const uint8_t* p = wk.dense[w].data() + (size_t)r * (size_t)cols[w] * (size_t)es_bytes;
if (es.dense[w]->dtype == "BF16")
for (int j = 0; j < cols[w]; ++j) rowf[(size_t)j] = bf16_to_f32(load_le16(p + 2 * j));
else if (es.dense[w]->dtype == "F16")
for (int j = 0; j < cols[w]; ++j) rowf[(size_t)j] = f16_to_f32(load_le16(p + 2 * j));
else if (es.dense[w]->dtype == "F32")
memcpy(rowf.data(), p, (size_t)cols[w] * 4);
else
HK_FAIL("%s: unsupported expert dtype %s", es.dense[w]->name.c_str(), es.dense[w]->dtype.c_str());
mxfp4_quantize_row(rowf.data(), cols[w], wk.scales[w].data() + (size_t)r * (size_t)(cols[w] / 32),
wk.packed[w].data() + (size_t)r * (size_t)(cols[w] / 2));
}
}
memcpy(rec + soff, wk.scales[w].data(), (size_t)nsc);
uint8_t* pl[4];
for (int p = 0; p < 4; ++p) pl[p] = rec + el.scale_bytes() + (int64_t)p * el.plane_bytes() + poff;
mxfp4_nibbles_to_planes(wk.packed[w].data(), rows[w], cols[w], pl[0], pl[1], pl[2], pl[3]);
mxfp4_accumulate_hist(wk.packed[w].data(), wk.scales[w].data(), rows[w], cols[w], wk.hist);
soff += nsc;
poff += npl;
}
}
});
for (int i = 0; i < nb; ++i) {
Work& wk = work[(size_t)i];
out.write(wk.record.data(), rec_bytes);
for (int c = 0; c < 8; ++c) hist[c] += wk.hist[c];
each_source(lp.mxfp4, lp.experts[(size_t)(e0 + i)], [&](const StTensor& t) { source.done(t); });
rep.expert_bytes += rec_bytes;
++rep.experts;
}
}
// magnitude tables for 1, 2 and 3 leading planes (4 planes are exact)
for (int k = 1; k <= 3; ++k) mxfp4_truncated_lut(hist, k, el.lut[k - 1]);
for (int i = 0; i < 8; ++i) el.lut[3][i] = kE2M1[i];
hkx_write_header(el, header.data());
out.write_at(0, header.data(), kHkxHeaderBytes);
out.close();
expert_layers.push_back(el);
++rep.expert_layers;
HK_INFO("layer %d: %d experts%s, %s in %.0f s%s", lp.layer, el.n_experts, lp.mxfp4 ? "" : " (requantized to MXFP4)",
human_bytes((double)(el.record_bytes() * el.n_experts)).c_str(), now_sec() - t_layer, room().c_str());
}
// ---- manifest, tokenizer files ---------------------------------------------
Json manifest = Store::make_manifest(src.config(), trunk, expert_layers, opt.src);
manifest.set("partial", partial);
write_text_file(path_join(opt.dst, "manifest.json"), manifest.dump(1));
{
std::string tok_dst = path_join(opt.dst, "tokenizer");
// tokenization_kimi.py is never run: it is only read to check the pre-tokenization pattern
const char* names[] = {"tiktoken.model", "tokenizer_config.json", "special_tokens_map.json", "tokenizer.json",
"chat_template.jinja", "generation_config.json", "tokenization_kimi.py"};
bool made = false;
for (const char* n : names) {
std::string p = path_join(opt.src, n);
if (!file_exists(p)) continue;
if (!made) make_dirs(tok_dst);
made = true;
std::error_code ec;
fs::copy_file(fs::u8path(p), fs::u8path(path_join(tok_dst, n)), fs::copy_options::overwrite_existing, ec);
if (ec) HK_WARN("could not copy %s: %s", n, ec.message().c_str());
}
}
rep.shards_deleted = source.deleted;
rep.shards_deleted_bytes = source.deleted_bytes;
rep.seconds = now_sec() - t0;
return rep;
}
} // namespace hk