File size: 7,483 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
#include "model/config.h"

#include "common/base.h"

namespace hk {

static std::vector<uint8_t> layer_set(const Json& list, int layers, const char* what) {
    // the config numbers layers from 1 (kda_layers [1, 2, 3, 5, ...]), tensors from 0
    std::vector<uint8_t> out((size_t)layers, 0);
    for (const Json& v : list.elems()) {
        int64_t one_based = v.as_int();
        HK_CHECK(one_based >= 1 && one_based <= layers, "%s lists layer %lld but the model has %d layers", what,
                 (long long)one_based, layers);
        out[(size_t)(one_based - 1)] = 1;
    }
    return out;
}

ModelConfig ModelConfig::from_json(const Json& config) {
    ModelConfig c;
    c.raw = config;
    const Json* text = config.find("text_config");
    const Json& t = (text && text->is_obj()) ? *text : config;
    c.prefix = (text && text->is_obj()) ? "language_model." : "";
    c.family = config.get_str("model_type", t.get_str("model_type", "unknown"));

    c.vocab = (int)t.at("vocab_size").as_int();
    c.hidden = (int)t.at("hidden_size").as_int();
    c.layers = (int)t.at("num_hidden_layers").as_int();
    c.rms_eps = (float)t.get_num("rms_norm_eps", 1e-6);
    c.bos = (int)t.get_int("bos_token_id", -1);
    c.eos = (int)t.get_int("eos_token_id", -1);
    c.pad = (int)t.get_int("pad_token_id", -1);
    c.max_positions = t.get_int("max_position_embeddings", 0);

    std::string act = t.get_str("hidden_act", "silu");
    HK_CHECK(act == "silu" || act == "situ", "unsupported hidden_act \"%s\"", act.c_str());
    c.situ = act == "situ";
    if (c.situ) {
        // same fallbacks as the reference
        c.situ_beta = (float)t.get_num("activation_situ_beta", 1.0);
        if (c.situ_beta == 0.0f) c.situ_beta = 1.0f;
        c.situ_lbeta = (float)t.get_num("activation_situ_linear_beta", 0.0);
    }
    c.intermediate = (int)t.get_int("intermediate_size", 0);

    c.n_experts = (int)t.get_int("num_experts", 0);
    c.top_k = (int)t.get_int("num_experts_per_token", 0);
    c.n_shared = (int)t.get_int("num_shared_experts", 0);
    c.moe_inter = (int)t.get_int("moe_intermediate_size", 0);
    c.first_dense = (int)t.get_int("first_k_dense_replace", 0);
    c.moe_layer_freq = (int)t.get_int("moe_layer_freq", 1);
    c.moe_renorm = t.get_bool("moe_renormalize", true);
    c.routed_scale = (float)t.get_num("routed_scaling_factor", 1.0);
    c.latent = (int)t.get_int("routed_expert_hidden_size", 0);
    c.latent_norm = t.get_bool("latent_moe_use_norm", false);
    std::string router = t.get_str("moe_router_activation_func", "sigmoid");
    HK_CHECK(router == "sigmoid", "unsupported router activation \"%s\" (only sigmoid is implemented)", router.c_str());
    HK_CHECK(t.get_int("num_expert_group", 1) == 1, "grouped expert routing (num_expert_group > 1) is not implemented");
    if (c.n_experts > 0) {
        HK_CHECK(c.top_k > 0 && c.top_k <= c.n_experts, "num_experts_per_token %d is invalid for %d experts", c.top_k,
                 c.n_experts);
        HK_CHECK(c.moe_inter > 0, "moe_intermediate_size is missing");
    }

    const Json* q = t.find("quantization_config");
    if (!q) q = config.find("quantization_config");
    if (q && q->is_obj()) {
        std::string fmt = q->get_str("format", "");
        c.expert_mxfp4 = fmt == "mxfp4-pack-quantized";
        HK_CHECK(c.expert_mxfp4, "unsupported quantization format \"%s\"", fmt.c_str());
    }

    c.heads = (int)t.get_int("num_attention_heads", 0);
    c.q_lora = (int)t.get_int("q_lora_rank", 0);
    c.kv_lora = (int)t.get_int("kv_lora_rank", 0);
    c.nope = (int)t.get_int("qk_nope_head_dim", 0);
    c.rope = (int)t.get_int("qk_rope_head_dim", 0);
    c.vdim = (int)t.get_int("v_head_dim", 0);
    c.mla_gate = t.get_bool("mla_use_output_gate", false);

    const Json* lin = t.find("linear_attn_config");
    if (lin && lin->is_obj()) {
        c.kda = layer_set(lin->at("kda_layers"), c.layers, "kda_layers");
        c.kda_heads = (int)lin->at("num_heads").as_int();
        c.kda_dim = (int)lin->at("head_dim").as_int();
        c.conv_k = (int)lin->at("short_conv_kernel_size").as_int();
        c.kda_full_gate = lin->get_bool("use_full_rank_gate", false);
        const Json* lb = lin->find("gate_lower_bound");
        if (lb && !lb->is_null()) {
            c.kda_bounded = true;
            c.kda_lower_bound = (float)lb->as_num();
        }
    } else {
        c.kda.assign((size_t)c.layers, 0);
    }
    bool any_mla = false;
    for (int L = 0; L < c.layers; ++L) any_mla = any_mla || !c.is_kda(L);
    if (any_mla) {
        HK_CHECK(c.heads > 0 && c.kv_lora > 0 && c.nope > 0 && c.vdim > 0 && c.rope > 0,
                 "the model has full-attention layers but its MLA dimensions are missing from the config");
        // every release of this family sets mla_use_nope: no rotary embedding anywhere
        HK_CHECK(t.get_bool("mla_use_nope", false), "MLA with rotary position embedding is not implemented (mla_use_nope must be true)");
    }

    c.ares_block = (int)t.get_int("attn_res_block_size", 0);

    const Json* dsa = t.find("dsa_config");
    if (dsa && dsa->is_obj()) {
        c.dsa = layer_set(dsa->at("dsa_layers"), c.layers, "dsa_layers");
        c.idx_topk = (int)dsa->at("index_topk").as_int();
        c.idx_heads = (int)dsa->at("index_num_heads").as_int();
        c.idx_dim = (int)dsa->at("index_head_dim").as_int();
        // these variants would change the math: refuse them instead of guessing
        HK_CHECK(dsa->get_int("index_topk_freq", 1) == 1, "index_topk_freq != 1 (shared indexers) is not implemented");
        HK_CHECK(dsa->get_int("index_rope_dim", 0) == 0, "an indexer with rotary dimensions is not implemented");
        HK_CHECK(dsa->get_str("index_k_norm_type", "layernorm") == "layernorm", "only a LayerNorm indexer key norm is implemented");
        for (int L = 0; L < c.layers; ++L)
            HK_CHECK(!(c.is_dsa(L) && c.is_kda(L)), "layer %d is listed as both KDA and DSA", L);
        HK_CHECK(c.q_lora > 0, "the sparse-attention indexer needs a factorized query (q_lora_rank)");
    }
    return c;
}

int ModelConfig::n_moe_layers() const {
    int n = 0;
    for (int L = 0; L < layers; ++L) n += is_moe(L) ? 1 : 0;
    return n;
}
int ModelConfig::n_kda_layers() const {
    int n = 0;
    for (int L = 0; L < layers; ++L) n += is_kda(L) ? 1 : 0;
    return n;
}

std::string ModelConfig::n_layer(int L, const char* tail) const { return strfmt("%smodel.layers.%d.%s", prefix.c_str(), L, tail); }

std::string ModelConfig::n_expert(int L, int e, int which) const {
    // the checkpoint calls the three matrices w1 (gate), w3 (up) and w2 (down)
    static const char* tags[3] = {"w1", "w3", "w2"};
    return strfmt("%smodel.layers.%d.block_sparse_moe.experts.%d.%s", prefix.c_str(), L, e, tags[which]);
}

std::string ModelConfig::summary() const {
    std::string s = strfmt("%s: %d layers (%d KDA, %d full attention%s), hidden %d, vocab %d", family.c_str(), layers,
                           n_kda_layers(), layers - n_kda_layers(), dsa.empty() ? "" : " with sparse indexer", hidden, vocab);
    if (n_experts > 0)
        s += strfmt("; MoE on %d layers: %d experts, %d per token, %d shared, expert %d x %d%s", n_moe_layers(), n_experts,
                    top_k, n_shared, moe_inter, expert_in(), expert_mxfp4 ? " (MXFP4)" : "");
    s += strfmt("; activation %s", situ ? "SiTU" : "SiLU");
    if (ares_block) s += strfmt("; AttnRes blocks of %d", ares_block);
    return s;
}

}  // namespace hk