diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index c41db4a8..82a3fc33 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -287,6 +287,7 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) { /* Dimensions come from GGUF's `.` keys, so one plugin covers a family; other keys * pass through in the free-form list. */ const std::string a = out->arch; + if (a == "hy_v3") out->arch = "hyv3"; auto gi = [&](const char* suffix, int64_t dflt) -> int64_t { int64_t v = 0; return g.get_i64(a + "." + suffix, &v) ? v : dflt; @@ -353,6 +354,36 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) { std::vector toks; if (g.get_strs("tokenizer.ggml.tokens", &toks)) m.n_vocab = (int64_t)toks.size(); if (m.n_vocab == 0) m.n_vocab = gi("vocab_size", 0); + if (a == "hy_v3") { + /* GGUF keeps reserved vocabulary rows beyond the tokenizer string array. The model matrices + * are authoritative for the row count (Hy-Memory has 120832 rows and 120818 strings). */ + const GgufTensor* emb = g.tensor("token_embd.weight"); + if (emb && emb->n_dims >= 2) m.n_vocab = emb->ne[1]; + + int64_t gating = 0, norm = 0; + double route_scale = 1.0; + g.get_i64("hy_v3.expert_gating_func", &gating); + g.get_i64("hy_v3.expert_weights_norm", &norm); + g.get_f64("hy_v3.expert_weights_scale", &route_scale); + const int64_t expert_width = gi("expert_feed_forward_length", 0); + const int64_t shared_width = gi("expert_shared_feed_forward_length", 0); + out->kv("qk_norm", g.tensor("blk.0.attn_q_norm.weight") && + g.tensor("blk.0.attn_k_norm.weight") ? "1" : "0"); + out->kv("moe_router_use_sigmoid", gating == 2 ? "1" : "0"); + out->kv("moe_router_enable_expert_bias", g.tensor("blk.1.exp_probs_b") ? "1" : "0"); + out->kv("enable_moe_fp32_combine", shared_width > 0 ? "1" : "0"); + out->kv("route_norm", norm ? "1" : "0"); + out->kv("router_scaling_factor", fmt("%.17g", route_scale)); + out->kv("first_k_dense_replace", g.tensor("blk.0.ffn_gate.weight") && + g.tensor("blk.1.ffn_gate_inp.weight") ? "1" : "0"); + out->kv("num_shared_experts", shared_width > 0 ? "1" : "0"); + out->kv("expert_hidden_dim", fmt("%lld", (long long)expert_width)); + out->kv("moe_intermediate_size", fmt("%lld", (long long)(2 * expert_width))); + out->kv("num_experts", fmt("%lld", (long long)m.n_expert)); + out->kv("num_experts_per_tok", fmt("%lld", (long long)m.n_expert_used)); + out->kv("attention_bias", "0"); + out->kv("mlp_bias", "0"); + } /* Everything else, stringified, for the plugin. Arrays are summarised (small integer arrays * spelled out); tokenizer keys are skipped, since the vocab has its own section. */ @@ -859,6 +890,33 @@ int Checkpoint::open_safetensors(const std::string& path) { RAD_TRY(add_companions()); RAD_TRY(add_torch_files()); } + /* HYV3's FP8 release indexes its static per-layer K/V cache descales as scalar F32 tensors in + * kv_cache_scales.safetensors. They are runtime attention parameters, not model weights; carry + * them through metadata so the architecture can bake them into kv_store and descale operands. */ + if (meta_.arch == "hyv3") { + for (int64_t l = 0; l < meta_.m.n_layers; ++l) { + for (const char* which : {"k", "v"}) { + const std::string source = "model.layers." + std::to_string(l) + + ".self_attn." + which + "_cache.scale"; + const SrcTensor* t = find(source); + if (!t) continue; + if (t->rad_dtype != RAD_F32 || !t->data || t->bytes < 4 || + (!t->shape.empty() && t->numel() != 1)) { + RAD_ERR("%s: HYV3 KV cache scale must be a scalar F32", source.c_str()); + return RAD_E_FORMAT; + } + float scale = 0.0f; + std::memcpy(&scale, t->data, sizeof scale); + if (!std::isfinite(scale) || scale <= 0.0f) { + RAD_ERR("%s: HYV3 KV cache scale must be positive and finite", source.c_str()); + return RAD_E_FORMAT; + } + char value[32]; + std::snprintf(value, sizeof value, "%.9g", (double)scale); + meta_.set("hyv3.kv_cache." + std::to_string(l) + "." + which + "_scale", value); + } + } + } /* FP8's block, where the checkpoint states one. */ if (const char* bs = meta_.get("quantization_config.weight_block_size")) { long long r = 0, c = 0; @@ -2302,9 +2360,9 @@ namespace { /* ---------------------------------------------------------------- GGUF block types * * ggml block types decodable to f32. Their geometry lives in core/text; decoding lives here, where - * weights are read. K-quants are refused rather than half-implemented. */ + * weights are read. Q4_K and Q6_K are the K-quants this HYV3 GGUF adapter needs. */ enum { GGML_F32 = 0, GGML_F16 = 1, GGML_Q4_0 = 2, GGML_Q4_1 = 3, GGML_Q5_0 = 6, GGML_Q5_1 = 7, - GGML_Q8_0 = 8, GGML_BF16 = 30 }; + GGML_Q8_0 = 8, GGML_Q4_K = 12, GGML_Q6_K = 14, GGML_BF16 = 30 }; int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) { auto half = [&](const uint8_t* q) { uint16_t h; std::memcpy(&h, q, 2); return rad_f16_to_f32(h); }; @@ -2357,6 +2415,45 @@ int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) { } } return RAD_OK; + case GGML_Q4_K: + for (int64_t b = 0; b < n / 256; ++b, p += 144) { + const float d = half(p), dmin = half(p + 2); + const uint8_t* scales = p + 4; + const uint8_t* qs = p + 16; + for (int j = 0; j < 8; ++j) { + uint32_t sc, mn; + if (j < 4) { + sc = scales[j] & 63u; + mn = scales[j + 4] & 63u; + } else { + sc = (scales[j + 4] & 15u) | ((uint32_t)(scales[j - 4] >> 6) << 4); + mn = (scales[j + 4] >> 4) | ((uint32_t)(scales[j] >> 6) << 4); + } + const float ds = d * (float)sc, ms = dmin * (float)mn; + for (int l = 0; l < 32; ++l) { + const int v = j * 32 + l; + const uint8_t q = qs[32 * (v / 64) + v % 32]; + const int code = (v % 64) < 32 ? q & 15 : q >> 4; + dst[b * 256 + v] = ds * (float)code - ms; + } + } + } + return RAD_OK; + case GGML_Q6_K: + for (int64_t b = 0; b < n / 256; ++b, p += 210) { + const uint8_t* ql = p; + const uint8_t* qh = p + 128; + const int8_t* scales = (const int8_t*)(p + 192); + const float d = half(p + 208); + for (int k = 0; k < 256; ++k) { + const int n128 = k / 128, t = (k % 128) / 32, l = k % 32; + const uint8_t lo = ql[64 * n128 + l + 32 * (t & 1)]; + const int code = (int)((t < 2 ? lo & 15 : lo >> 4) | + (((qh[32 * n128 + l] >> (2 * t)) & 3) << 4)); + dst[b * 256 + k] = d * (float)scales[k / 16] * (float)(code - 32); + } + } + return RAD_OK; default: return RAD_E_UNSUPPORTED; } diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp index b7562c68..89fdb984 100644 --- a/tests/checkpoint_test.cpp +++ b/tests/checkpoint_test.cpp @@ -89,6 +89,12 @@ T bf16(const std::string& name, std::vector shape, float tag) { return t; } +T cache_scale_f32(const std::string& name, float value) { + T t{ name, "F32", {1}, std::vector(4) }; + std::memcpy(t.bytes.data(), &value, sizeof value); + return t; +} + T fp8(const std::string& name, std::vector shape) { T t{ name, "F8_E4M3", shape, {} }; int64_t n = 1; @@ -1685,6 +1691,53 @@ struct ConfigCase { } /* namespace */ +TEST(hyv3_static_kv_cache_scales_are_carried_into_model_metadata) { + const std::string dir = fresh_dir(); + write_file(dir + "/config.json", R"({"model_type":"hy_v3","num_hidden_layers":1})"); + write_shard(dir + "/kv_cache_scales.safetensors", { + cache_scale_f32("model.layers.0.self_attn.k_cache.scale", 0.0376674123f), + cache_scale_f32("model.layers.0.self_attn.v_cache.scale", 0.0004359654f), + }); + write_file(dir + "/model.safetensors.index.json", + R"({"weight_map":{"model.layers.0.self_attn.k_cache.scale":"kv_cache_scales.safetensors","model.layers.0.self_attn.v_cache.scale":"kv_cache_scales.safetensors"}})"); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + const char* k = ck.meta().get("hyv3.kv_cache.0.k_scale"); + const char* v = ck.meta().get("hyv3.kv_cache.0.v_scale"); + REQUIRE(k && v); + CHECK(std::fabs(std::strtod(k, nullptr) - 0.0376674123) < 1e-9); + CHECK(std::fabs(std::strtod(v, nullptr) - 0.0004359654) < 1e-10); + std::filesystem::remove_all(dir); +} + +TEST(hyv3_static_kv_cache_scales_reject_invalid_values_and_shapes) { + const char* name = "model.layers.0.self_attn.k_cache.scale"; + std::vector invalid; + for (float value : {0.0f, -1.0f, NAN, INFINITY}) + invalid.push_back(cache_scale_f32(name, value)); + invalid.push_back(bf16(name, {1}, 1.0f)); + T nonscalar = cache_scale_f32(name, 1.0f); + nonscalar.shape = {2}; + nonscalar.bytes.resize(8); + invalid.push_back(std::move(nonscalar)); + for (const T& t : invalid) { + const std::string dir = write_checkpoint({t}, + R"({"model_type":"hy_v3","num_hidden_layers":1})"); + Checkpoint ck; + CHECK_EQ(ck.open(dir), RAD_E_FORMAT); + } + /* A true rank-zero scalar and a one-element vector both satisfy the checkpoint contract. */ + T scalar = cache_scale_f32(name, 0.5f); + scalar.shape.clear(); + const std::string dir = write_checkpoint({scalar}, + R"({"model_type":"hy_v3","num_hidden_layers":1})"); + Checkpoint ck; + CHECK_OK(ck.open(dir)); + const char* scale = ck.meta().get("hyv3.kv_cache.0.k_scale"); + REQUIRE(scale != nullptr); + CHECK_EQ(std::strtod(scale, nullptr), 0.5); +} + TEST(config_json_fills_the_model_meta_as_each_family_spells_it) { const ConfigCase cases[] = { { "a multimodal MoE: text_config first, head_dim read rather than derived, the expert " @@ -1816,8 +1869,7 @@ TEST(a_concat_declared_in_pieces_joins_every_piece_in_order) { /* ================================================================== GGUF as a source * * A GGUF tensor's dimensions are stored fastest first and are reversed once into the row-major - * shape everything else uses; the legacy block types decode by their definitions; a K-quant is - * refused with its name, not decoded as something else. */ + * shape everything else uses; the legacy and Q4_K/Q6_K block types decode by their definitions. */ namespace { struct GKv { @@ -1952,7 +2004,22 @@ TEST(a_gguf_tensor_is_row_major_and_its_legacy_blocks_decode_by_definition) { const std::string dir = fresh_dir(); const std::string path = dir + "/m.gguf"; std::vector w8, w40, w41, w50, w51; - GTensor k4{ "t.q4_k", 12, { 256, 2 }, std::vector(2 * 144, 0) }; + std::vector q4k(144, 0); + const uint16_t q4d = h16(0.5f), q4min = h16(0.25f); + std::memcpy(q4k.data(), &q4d, 2); + std::memcpy(q4k.data() + 2, &q4min, 2); + const uint8_t q4scales[12] = {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, + 0x47, 0x48, 0x21, 0x32, 0x43, 0x54}; + std::memcpy(q4k.data() + 4, q4scales, sizeof q4scales); + q4k[16] = 0x21; /* low/high nibbles of values 0 and 32 */ + q4k[16 + 64] = 0x32; /* values 128 and 160, including packed high scale bits */ + GTensor k4{ "t.q4_k", 12, { 256, 1 }, q4k }; + std::vector q6k(210, 0); + const uint16_t q6d = h16(0.5f); + std::memcpy(q6k.data() + 208, &q6d, 2); + q6k[0] = 0x21; q6k[32] = 0x43; q6k[128] = 0xD3; + q6k[192] = 2; q6k[194] = 3; q6k[196] = 4; q6k[198] = 5; + GTensor k6{ "t.q6_k", 14, { 256, 1 }, q6k }; GTensor f16{ "t.f16", 1, { 64, 4, 2 }, {} }; for (int i = 0; i < 64 * 4 * 2; ++i) { const uint16_t v = h16((float)i * 0.5f); @@ -1962,7 +2029,7 @@ TEST(a_gguf_tensor_is_row_major_and_its_legacy_blocks_decode_by_definition) { write_gguf(path, llama_kvs(7), { legacy_blocks("t.q8_0", 8, &w8), legacy_blocks("t.q4_0", 2, &w40), legacy_blocks("t.q4_1", 3, &w41), legacy_blocks("t.q5_0", 6, &w50), - legacy_blocks("t.q5_1", 7, &w51), k4, f16 }); + legacy_blocks("t.q5_1", 7, &w51), k4, k6, f16 }); Checkpoint ck; REQUIRE_EQ(ck.open(path), RAD_OK); CHECK(ck.is_gguf()); @@ -1974,6 +2041,7 @@ TEST(a_gguf_tensor_is_row_major_and_its_legacy_blocks_decode_by_definition) { { "t.q5_1", &w51 } }; for (const auto& l : legacy) prog.name_map.push_back(map(l.name, RAD_MAP_COPY, { l.name })); prog.name_map.push_back(map("t.q4_k", RAD_MAP_COPY, { "t.q4_k" })); + prog.name_map.push_back(map("t.q6_k", RAD_MAP_COPY, { "t.q6_k" })); prog.name_map.push_back(map("t.f16", RAD_MAP_COPY, { "t.f16" })); std::string why; for (const auto& l : legacy) { @@ -1997,11 +2065,24 @@ TEST(a_gguf_tensor_is_row_major_and_its_legacy_blocks_decode_by_definition) { { CkptWeight w; REQUIRE_EQ(ckpt_resolve(ck, prog, "t.q4_k", false, &w, &why), RAD_OK); - CHECK_EQ(w.shape[0], (int64_t)2); + CHECK_EQ(w.shape[0], (int64_t)1); CHECK_EQ(w.shape[1], (int64_t)256); std::vector f(256); - CHECK_EQ(ckpt_rows_f32(w, 0, 1, f.data(), &why), (int)RAD_E_UNSUPPORTED); - CHECK(has(why, "q4_K")); + REQUIRE_EQ(ckpt_rows_f32(w, 0, 1, f.data(), &why), RAD_OK); + CHECK_EQ(f[0], -0.75f); + CHECK_EQ(f[32], 0.5f); + CHECK_EQ(f[128], 12.5f); + CHECK_EQ(f[160], 22.25f); + } + { + CkptWeight w; + REQUIRE_EQ(ckpt_resolve(ck, prog, "t.q6_k", false, &w, &why), RAD_OK); + std::vector f(256); + REQUIRE_EQ(ckpt_rows_f32(w, 0, 1, f.data(), &why), RAD_OK); + CHECK_EQ(f[0], 17.0f); + CHECK_EQ(f[32], -43.5f); + CHECK_EQ(f[64], -28.0f); + CHECK_EQ(f[96], 50.0f); } { /* A plain f16 tensor of rank 3 is trivial and reversed in every dimension. */ @@ -2045,6 +2126,59 @@ TEST(a_gguf_tensor_is_row_major_and_its_legacy_blocks_decode_by_definition) { } } +TEST(hyv3_gguf_metadata_normalizes_architecture_and_config_fields) { + const std::string path = fresh_dir() + "/hyv3.gguf"; + const std::vector kvs = { + { "general.architecture", 8, 0, { "hy_v3" } }, + { "hy_v3.block_count", 4, 2, {} }, + { "hy_v3.embedding_length", 4, 4, {} }, + { "hy_v3.attention.head_count", 4, 2, {} }, + { "hy_v3.attention.head_count_kv", 4, 1, {} }, + { "hy_v3.attention.key_length", 4, 2, {} }, + { "hy_v3.feed_forward_length", 4, 8, {} }, + { "hy_v3.context_length", 4, 1024, {} }, + { "hy_v3.expert_count", 4, 4, {} }, + { "hy_v3.expert_used_count", 4, 2, {} }, + { "hy_v3.expert_feed_forward_length", 4, 2, {} }, + { "hy_v3.expert_shared_feed_forward_length", 4, 2, {} }, + { "hy_v3.expert_weights_norm", 4, 1, {} }, + { "hy_v3.expert_weights_scale", 6, 2.826, {} }, + { "hy_v3.expert_gating_func", 4, 2, {} }, + { "hy_v3.attention.layer_norm_rms_epsilon", 6, 1e-5, {} }, + { "hy_v3.rope.freq_base", 6, 11158840.0, {} }, + { "tokenizer.ggml.tokens", 9, 0, { "a", "b" } }, + { "general.file_type", 4, 15, {} }, + }; + auto f32 = [](const char* name, std::vector ne) { + size_t count = 1; + for (uint64_t d : ne) count *= (size_t)d; + return GTensor{ name, 0, std::move(ne), std::vector(count * sizeof(float), 0) }; + }; + write_gguf(path, kvs, { f32("token_embd.weight", {4, 4}), + f32("blk.0.attn_q_norm.weight", {2}), + f32("blk.0.attn_k_norm.weight", {2}), + f32("blk.0.ffn_gate.weight", {4, 4}), + f32("blk.1.ffn_gate_inp.weight", {4, 4}), + f32("blk.1.exp_probs_b", {4}) }); + Checkpoint ck; + REQUIRE_EQ(ck.open(path), RAD_OK); + CHECK_EQ(ck.meta().arch, std::string("hyv3")); + CHECK_EQ(ck.meta().quant, std::string("gguf_ftype_15")); + CHECK_EQ(ck.meta().m.n_vocab, (int64_t)4); /* matrix rows exceed tokenizer strings */ + CHECK_EQ(std::string(ck.meta().get("qk_norm")), std::string("1")); + CHECK_EQ(std::string(ck.meta().get("moe_router_use_sigmoid")), std::string("1")); + CHECK_EQ(std::string(ck.meta().get("moe_router_enable_expert_bias")), std::string("1")); + CHECK_EQ(std::string(ck.meta().get("enable_moe_fp32_combine")), std::string("1")); + CHECK_EQ(std::string(ck.meta().get("route_norm")), std::string("1")); + CHECK_EQ(std::string(ck.meta().get("first_k_dense_replace")), std::string("1")); + CHECK_EQ(std::string(ck.meta().get("num_shared_experts")), std::string("1")); + CHECK_EQ(std::string(ck.meta().get("expert_hidden_dim")), std::string("2")); + CHECK_EQ(std::string(ck.meta().get("moe_intermediate_size")), std::string("4")); + CHECK_EQ(std::string(ck.meta().get("num_experts")), std::string("4")); + CHECK_EQ(std::string(ck.meta().get("num_experts_per_tok")), std::string("2")); + CHECK_EQ(ck.meta().get("router_scaling_factor") != nullptr, true); +} + /* ================================================================== a diffusers pipeline * * model_index.json and one folder per component read as one checkpoint: the text encoder's