hkimi / src /model /weights.cpp
Ozomozyan's picture
hkimi 0.1.0
68888be verified
Raw History Blame Contribute Delete
13.3 kB
#include "model/weights.h"
#include <cstdlib>
#include <cstring>
#include "common/base.h"
namespace hk {
std::vector<TensorNeed> layer_tensors(const ModelConfig& c, int L) {
std::vector<TensorNeed> v;
auto add = [&](const char* tail, Part p) { v.push_back({c.n_layer(L, tail), p}); };
add("input_layernorm.weight", Part::Attn);
if (c.ares_block) {
if (L > 0) { // layer 0 has no earlier block to attend to before its attention
add("self_attention_res_norm.weight", Part::Attn);
add("self_attention_res_proj.weight", Part::Attn);
}
add("mlp_res_norm.weight", Part::Attn);
add("mlp_res_proj.weight", Part::Attn);
}
if (c.is_kda(L)) {
for (const char* n : {"q", "k", "v"}) {
add(strfmt("self_attn.%s_proj.weight", n).c_str(), Part::Attn);
add(strfmt("self_attn.%s_conv1d.weight", n).c_str(), Part::Attn);
}
add("self_attn.f_a_proj.weight", Part::Attn);
add("self_attn.f_b_proj.weight", Part::Attn);
add("self_attn.A_log", Part::Attn);
add("self_attn.dt_bias", Part::Attn);
add("self_attn.b_proj.weight", Part::Attn);
if (c.kda_full_gate) {
add("self_attn.g_proj.weight", Part::Attn);
} else {
add("self_attn.g_a_proj.weight", Part::Attn);
add("self_attn.g_b_proj.weight", Part::Attn);
}
add("self_attn.o_norm.weight", Part::Attn);
add("self_attn.o_proj.weight", Part::Attn);
} else {
if (c.q_lora > 0) {
add("self_attn.q_a_proj.weight", Part::Attn);
add("self_attn.q_a_layernorm.weight", Part::Attn);
add("self_attn.q_b_proj.weight", Part::Attn);
} else {
add("self_attn.q_proj.weight", Part::Attn);
}
add("self_attn.kv_a_proj_with_mqa.weight", Part::Attn);
add("self_attn.kv_a_layernorm.weight", Part::Attn);
add("self_attn.kv_b_proj.weight", Part::Attn);
if (c.mla_gate) add("self_attn.g_proj.weight", Part::Attn);
add("self_attn.o_proj.weight", Part::Attn);
if (c.is_dsa(L)) {
add("self_attn.indexer.wq_b.weight", Part::Attn);
add("self_attn.indexer.wk.weight", Part::Attn);
add("self_attn.indexer.k_norm.weight", Part::Attn);
add("self_attn.indexer.k_norm.bias", Part::Attn);
add("self_attn.indexer.weights_proj.weight", Part::Attn);
}
}
add("post_attention_layernorm.weight", Part::Ffn);
if (c.is_moe(L)) {
add("block_sparse_moe.gate.weight", Part::Ffn);
add("block_sparse_moe.gate.e_score_correction_bias", Part::Ffn);
if (c.latent > 0) {
add("block_sparse_moe.routed_expert_down_proj.weight", Part::Ffn);
add("block_sparse_moe.routed_expert_up_proj.weight", Part::Ffn);
if (c.latent_norm) add("block_sparse_moe.routed_expert_norm.weight", Part::Ffn);
}
if (c.n_shared > 0) {
add("block_sparse_moe.shared_experts.gate_proj.weight", Part::Ffn);
add("block_sparse_moe.shared_experts.up_proj.weight", Part::Ffn);
add("block_sparse_moe.shared_experts.down_proj.weight", Part::Ffn);
}
} else {
add("mlp.gate_proj.weight", Part::Ffn);
add("mlp.up_proj.weight", Part::Ffn);
add("mlp.down_proj.weight", Part::Ffn);
}
return v;
}
std::vector<TensorNeed> head_tensors(const ModelConfig& c) {
std::vector<TensorNeed> v;
v.push_back({c.n_final_norm(), Part::Head});
if (c.ares_block) {
v.push_back({c.n_model("output_attn_res_norm.weight"), Part::Head});
v.push_back({c.n_model("output_attn_res_proj.weight"), Part::Head});
}
v.push_back({c.n_lm_head(), Part::Head});
return v;
}
static bool starts_with(const std::string& s, const std::string& p) { return s.compare(0, p.size(), p) == 0; }
static bool ends_with(const std::string& s, const std::string& p) {
return s.size() >= p.size() && s.compare(s.size() - p.size(), p.size(), p) == 0;
}
bool tensor_is_ignorable(const ModelConfig& c, const std::string& name) {
// vision pathway: the engine is text-only
if (starts_with(name, "vision_tower.") || starts_with(name, "mm_projector.")) return true;
if (name.find(".vision_tower.") != std::string::npos || name.find(".mm_projector.") != std::string::npos) return true;
// layer 0 never mixes earlier blocks before its attention: these exist but are not read
std::string l0 = c.n_layer(0, "self_attention_res_");
if (starts_with(name, l0)) return true;
// compressed-tensors bookkeeping next to packed weights
if (ends_with(name, ".weight_shape")) return true;
return false;
}
void WeightSet::put(const std::string& name, Weight* w) {
auto& slot = weights_[name];
if (!slot) {
slot.reset(new Entry());
slot->name = name;
} else if (slot->w) {
bk_->unload(slot->w);
}
slot->w = w;
}
const Weight* WeightSet::find(const std::string& name) const {
auto it = weights_.find(name);
return it == weights_.end() ? nullptr : it->second->w;
}
const Weight* WeightSet::get(const std::string& name) const {
const Weight* w = find(name);
HK_CHECK(w != nullptr, "tensor %s is not loaded", name.c_str());
return w;
}
Lin WeightSet::lin(const std::string& name) const {
auto it = weights_.find(name);
HK_CHECK(it != weights_.end() && it->second->w, "tensor %s is not loaded", name.c_str());
Lin l;
l.w = it->second->w;
l.name = &it->second->name;
return l;
}
void WeightSet::erase(const std::string& name) {
auto it = weights_.find(name);
if (it == weights_.end()) return;
if (it->second->w) bk_->unload(it->second->w);
weights_.erase(it);
}
void WeightSet::clear() {
for (auto& kv : weights_) {
if (kv.second->w) bk_->unload(kv.second->w);
}
weights_.clear();
}
static void expect(const Weight* w, int rows, int cols, const std::string& name) {
HK_CHECK(w->desc.rows == rows && w->desc.cols == cols, "%s has shape %d x %d but the config implies %d x %d", name.c_str(),
w->desc.rows, w->desc.cols, rows, cols);
}
// vectors (norm weights, biases) load as [1, n]; checkpoints store them as [n, 1] or [1, n]
static void expect_vec(const Weight* w, int n, const std::string& name) {
HK_CHECK((int64_t)w->desc.rows * w->desc.cols >= n, "%s has %lld elements but the config implies at least %d", name.c_str(),
(long long)w->desc.rows * w->desc.cols, n);
}
LayerW bind_layer(const ModelConfig& c, int L, const WeightSet& s, bool attn, bool ffn) {
LayerW w;
w.layer = L;
w.kda = c.is_kda(L);
w.moe = c.is_moe(L);
auto N = [&](const char* tail) { return c.n_layer(L, tail); };
auto lin = [&](const char* tail, int rows, int cols) {
Lin l = s.lin(N(tail));
expect(l.w, rows, cols, N(tail));
return l;
};
auto vec = [&](const char* tail, int n) {
const Weight* x = s.get(N(tail));
expect_vec(x, n, N(tail));
return x;
};
const int d = c.hidden;
if (attn) {
w.in_norm = vec("input_layernorm.weight", d);
if (c.ares_block) {
if (L > 0) {
w.ar_attn_norm = vec("self_attention_res_norm.weight", d);
w.ar_attn_proj = vec("self_attention_res_proj.weight", d);
}
w.ar_mlp_norm = vec("mlp_res_norm.weight", d);
w.ar_mlp_proj = vec("mlp_res_proj.weight", d);
}
if (w.kda) {
KdaW& k = w.kdaw;
const int HD = c.kda_heads * c.kda_dim;
k.q = lin("self_attn.q_proj.weight", HD, d);
k.k = lin("self_attn.k_proj.weight", HD, d);
k.v = lin("self_attn.v_proj.weight", HD, d);
k.qc = s.get(N("self_attn.q_conv1d.weight"));
k.kc = s.get(N("self_attn.k_conv1d.weight"));
k.vc = s.get(N("self_attn.v_conv1d.weight"));
for (const Weight* cw : {k.qc, k.kc, k.vc}) expect(cw, HD, c.conv_k, N("self_attn.*_conv1d.weight"));
k.f_a = s.lin(N("self_attn.f_a_proj.weight"));
k.f_b = s.lin(N("self_attn.f_b_proj.weight"));
HK_CHECK(k.f_a.w->desc.cols == d && k.f_b.w->desc.rows == HD && k.f_b.w->desc.cols == k.f_a.w->desc.rows,
"layer %d: decay gate projections f_a / f_b have unexpected shapes", L);
k.A_log = vec("self_attn.A_log", c.kda_heads);
k.dt_bias = vec("self_attn.dt_bias", HD);
k.b = lin("self_attn.b_proj.weight", c.kda_heads, d);
if (c.kda_full_gate) {
k.g = lin("self_attn.g_proj.weight", HD, d);
} else {
k.g_a = s.lin(N("self_attn.g_a_proj.weight"));
k.g_b = s.lin(N("self_attn.g_b_proj.weight"));
HK_CHECK(k.g_a.w->desc.cols == d && k.g_b.w->desc.rows == HD && k.g_b.w->desc.cols == k.g_a.w->desc.rows,
"layer %d: output gate projections g_a / g_b have unexpected shapes", L);
}
k.o_norm = vec("self_attn.o_norm.weight", c.kda_dim);
k.o = lin("self_attn.o_proj.weight", d, HD);
} else {
MlaW& m = w.mlaw;
const int H = c.heads, qd = c.qdim();
if (c.q_lora > 0) {
m.q_a = lin("self_attn.q_a_proj.weight", c.q_lora, d);
m.q_a_norm = vec("self_attn.q_a_layernorm.weight", c.q_lora);
m.q_b = lin("self_attn.q_b_proj.weight", H * qd, c.q_lora);
} else {
m.q = lin("self_attn.q_proj.weight", H * qd, d);
}
m.kv_a = lin("self_attn.kv_a_proj_with_mqa.weight", c.kv_lora + c.rope, d);
m.kv_a_norm = vec("self_attn.kv_a_layernorm.weight", c.kv_lora);
m.kv_b = s.get(N("self_attn.kv_b_proj.weight"));
expect(m.kv_b, H * (c.nope + c.vdim), c.kv_lora, N("self_attn.kv_b_proj.weight"));
if (c.mla_gate) m.g = lin("self_attn.g_proj.weight", H * c.vdim, d);
m.o = lin("self_attn.o_proj.weight", d, H * c.vdim);
if (c.is_dsa(L)) {
m.idx_q = lin("self_attn.indexer.wq_b.weight", c.idx_heads * c.idx_dim, c.q_lora);
m.idx_k = lin("self_attn.indexer.wk.weight", c.idx_dim, d);
m.idx_w = lin("self_attn.indexer.weights_proj.weight", c.idx_heads, d);
m.idx_norm_w = vec("self_attn.indexer.k_norm.weight", c.idx_dim);
m.idx_norm_b = vec("self_attn.indexer.k_norm.bias", c.idx_dim);
}
}
}
if (ffn) {
w.post_norm = vec("post_attention_layernorm.weight", d);
if (w.moe) {
MoeW& m = w.moew;
m.gate = lin("block_sparse_moe.gate.weight", c.n_experts, d);
m.bias = vec("block_sparse_moe.gate.e_score_correction_bias", c.n_experts);
if (c.latent > 0) {
m.down = lin("block_sparse_moe.routed_expert_down_proj.weight", c.latent, d);
m.up = lin("block_sparse_moe.routed_expert_up_proj.weight", d, c.latent);
if (c.latent_norm) m.latent_norm = vec("block_sparse_moe.routed_expert_norm.weight", c.latent);
}
if (c.n_shared > 0) {
const int si = c.n_shared * c.moe_inter;
m.sh_gate = lin("block_sparse_moe.shared_experts.gate_proj.weight", si, d);
m.sh_up = lin("block_sparse_moe.shared_experts.up_proj.weight", si, d);
m.sh_down = lin("block_sparse_moe.shared_experts.down_proj.weight", d, si);
}
} else {
w.mlp_gate = lin("mlp.gate_proj.weight", c.intermediate, d);
w.mlp_up = lin("mlp.up_proj.weight", c.intermediate, d);
w.mlp_down = lin("mlp.down_proj.weight", d, c.intermediate);
}
}
return w;
}
void split_tensor_name(const std::string& name, int* layer, std::string* kind) {
*layer = -1;
std::string rest = name;
const size_t at = name.find("layers.");
size_t i = at == std::string::npos ? 0 : at + 7, j = i;
while (at != std::string::npos && j < name.size() && name[j] >= '0' && name[j] <= '9') ++j;
if (at != std::string::npos && j > i && j < name.size() && name[j] == '.') {
*layer = atoi(name.substr(i, j - i).c_str());
rest = name.substr(j + 1);
} else {
// outside the layers: drop the wrappers ("language_model.model.norm.weight" -> "norm")
for (const char* prefix : {"language_model.", "model."})
if (rest.compare(0, strlen(prefix), prefix) == 0) rest = rest.substr(strlen(prefix));
}
if (rest.size() > 7 && rest.compare(rest.size() - 7, 7, ".weight") == 0) rest.resize(rest.size() - 7);
*kind = rest;
}
HeadW bind_head(const ModelConfig& c, const WeightSet& s) {
HeadW h;
h.norm = s.get(c.n_final_norm());
expect_vec(h.norm, c.hidden, c.n_final_norm());
if (c.ares_block) {
h.ar_norm = s.get(c.n_model("output_attn_res_norm.weight"));
h.ar_proj = s.get(c.n_model("output_attn_res_proj.weight"));
}
h.lm_head = s.lin(c.n_lm_head());
expect(h.lm_head.w, c.vocab, c.hidden, c.n_lm_head());
return h;
}
} // namespace hk