Files
2026-10-29 20:48:09 +07:00

943 lines
47 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// gguf_model.cpp — импорт/экспорт/ре-квантование моделей Xenith в контейнере GGUF.
//
// Раскладка весов. В ggml/GGUF тензор хранится row-major, dims[0] (ne0) —
// НЕПРЕРЫВНАЯ ось (входные признаки), строка = выходной признак:
// W_ggml[out][in]. Xenith для gemm_nn(x, W) хранит W[in][out], поэтому
// матрицы q/k/v/o/ffn при экспорте ТРАНСПОНИРУЮТСЯ. Эмбеддинги
// (token_embd/output) уже лежат как [vocab][n_embd] — копируются без zmian.
#include "gguf_model.h"
#include "safetensors.h"
#include "config.h" // engine_info/engine_warn
#include "model.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <map>
#include <unordered_map>
namespace xt {
namespace {
// ---------------------------------------------------------------------------
// Вспомогательное
// ---------------------------------------------------------------------------
std::string lower_str(const std::string& s) {
std::string r = s;
for (char& c : r) c = (char)std::tolower((unsigned char)c);
return r;
}
bool ends_with(const std::string& s, const std::string& suf) {
return s.size() >= suf.size() && s.compare(s.size() - suf.size(), suf.size(), suf) == 0;
}
// Перестановка выходов RoPE между раскладками (внутри каждой головы):
// ggml/llama «rotate-half»: пара (i, i+hd/2), частота base^(-2i/hd)
// Xenith «interleaved»: пара (2i, 2i+1), частота base^(-2i/hd)
// Частоты совпадают → достаточно переставить строки/колонки Q и K;
// скалярное произведение q·k инвариантно (перестановка 적용лена к обоим).
// half→interleaved (импорт): xen[2i] = g[j], xen[2i+1] = g[j+half]
// interleaved→half (экспорт): g[j] = xen[2i], g[j+half] = xen[2i+1]
// data — плоский буфер в раскладке Xenith [R строк][C колонок], C = out = H*hd.
// to_xenith=true: half→interleaved (импорт из ggml), false: interleaved→half (экспорт).
void rope_permute_xenith(float* data, int64_t R, int64_t C, int n_head, bool to_xenith) {
if (n_head <= 0) return;
const int64_t hd = C / n_head;
const int64_t half = hd / 2;
if (hd % 2 != 0 || half <= 0 || hd * n_head != C) return;
std::vector<float> tmp((size_t)hd);
for (int64_t i = 0; i < R; ++i) {
for (int64_t h = 0; h < n_head; ++h) {
float* base = data + (size_t)i * (size_t)C + (size_t)h * (size_t)hd;
std::memcpy(tmp.data(), base, (size_t)hd * sizeof(float));
for (int64_t j = 0; j < half; ++j) {
if (to_xenith) { // half -> interleaved
base[2 * j] = tmp[j];
base[2 * j + 1] = tmp[j + half];
} else { // interleaved -> half
base[j] = tmp[2 * j];
base[j + half] = tmp[2 * j + 1];
}
}
}
}
}
// out[o*R + i] = t(i, o): Xenith [in][out] → ggml [out][in] (dims {R=in, C=out}).
void transpose_to_ggml(const Tensor& t, std::vector<float>& out) {
const int64_t R = t.R(), C = t.C();
out.resize((size_t)R * (size_t)C);
const float* src = t.ptr();
for (int64_t o = 0; o < C; ++o)
for (int64_t i = 0; i < R; ++i)
out[(size_t)o * (size_t)R + (size_t)i] = src[(size_t)i * (size_t)C + (size_t)o];
}
void plain_copy(const Tensor& t, std::vector<float>& out) {
out.assign(t.ptr(), t.ptr() + t.n());
}
std::string blk_name(int L, const char* what) {
char b[64];
snprintf(b, sizeof b, "blk.%d.%s", L, what);
return b;
}
// Материализовать веса с GPU на хост перед записью файла (как в save_checkpoint).
void materialize_params(const Params& p) {
if (!backend_is_gpu()) return;
std::vector<Tensor*> mats;
for (const Tensor* t : p.all()) mats.push_back(const_cast<Tensor*>(t));
backend()->materialize(mats);
}
// ---------------------------------------------------------------------------
// Чтение конфигурации из GGUF (xenith / llama)
// ---------------------------------------------------------------------------
struct ArchConfig {
Config cfg;
int n_kv_head = 0; // llama: attention.head_count_kv (0 = не задан → MHA)
bool tied = true;
bool has_output_weight = false;
std::string tokenizer_model; // tokenizer.ggml.model
std::vector<std::string> tokens; // tokenizer.ggml.tokens
std::vector<std::string> merges; // tokenizer.ggml.merges
std::vector<int32_t> token_types; // tokenizer.ggml.token_type
int bos = 1, eos = 2, unk = 0, user = -1, asst = -1, nl = -1;
BpeKind bpe_kind = BpeKind::None;
bool encode_adds_bos = true;
bool encode_appends_eos = true;
int step = 0; float loss = 0; uint64_t seed = 1337;
std::string arch;
};
// Прочитать арх-специфичные ключи + словарь. Веса НЕ трогаем.
bool read_arch_config(const GgufFile& g, ArchConfig& a, std::string& err) {
a.arch = g.get_str("general.architecture", "");
if (a.arch.empty()) {
// угадываем по набору тензоров
if (g.find_tensor("token_embd.weight") && g.find_tensor("blk.0.attn_q.weight"))
a.arch = "llama";
}
if (a.arch != "xenith" && a.arch != "llama") {
err = "архитектура '" + (a.arch.empty() ? std::string("<не указана>") : a.arch) +
"' не поддерживается: Xenith понимает GGUF собственных моделей (xenith) "
"и LLaMA-подобные (llama: RoPE + RMSNorm + SwiGLU, MHA)";
return false;
}
const std::string pfx = a.arch + ".";
auto key = [&](const char* k) { return pfx + k; };
a.cfg.n_layer = (int)g.get_int(key("block_count"), 0);
a.cfg.n_embd = (int)g.get_int(key("embedding_length"), 0);
a.cfg.n_head = (int)g.get_int(key("attention.head_count"), 0);
a.cfg.block_size = (int)g.get_int(key("context_length"), 2048);
a.cfg.ffn_dim = (int)g.get_int(key("feed_forward_length"), 0);
a.cfg.rope_base = (int)std::lround(g.get_flt(key("rope.freq_base"), 10000.0));
a.cfg.rms_eps = (float)g.get_flt(key("attention.layer_norm_rms_epsilon"), 1e-5);
if (a.arch == "xenith") {
a.cfg.init_std = (float)g.get_flt("xenith.init_std", 0.02f);
a.cfg.n_vocab_out = (int)g.get_int("xenith.vocab_out", 0);
a.step = (int)g.get_int("xenith.training_step", 0);
a.loss = (float)g.get_flt("xenith.training_loss", 0.0f);
a.seed = (uint64_t)g.get_int("xenith.seed", 1337);
// Xenith хранит ffn_dim = 0 как «авто (= 4*n_embd)»; GGUF всегда несёт
// явное значение. Возвращаем 0, чтобы round-trip xnh→gguf→xnh был
// побайтово точным и для конфига.
if (a.cfg.ffn_dim == 4 * a.cfg.n_embd) a.cfg.ffn_dim = 0;
} else {
a.cfg.init_std = 0.02f;
// GQA: Xenith считает чистый MHA, поэтому K/V-головы при импорте
// РАЗВЁРТЫВАЮТСЯ (каждая kv-голова копируется на свою группу q-голов).
// Для инференса это математически точно; при дообучении копии живут
// как независимые головы (документировано).
a.n_kv_head = (int)g.get_int("llama.attention.head_count_kv", a.cfg.n_head);
if (a.n_kv_head <= 0 || a.cfg.n_head % a.n_kv_head != 0) {
err = "attention.head_count_kv = " + std::to_string(a.n_kv_head) +
" не делит head_count = " + std::to_string(a.cfg.n_head);
return false;
}
if (g.get_int("llama.expert_count", 0) > 0) {
err = "MoE-модели (expert_count > 0) не поддерживаются";
return false;
}
const int64_t rope_dim = g.get_int("llama.rope.dimension_count", -1);
if (rope_dim > 0 && a.cfg.n_head > 0 && rope_dim != a.cfg.n_embd / a.cfg.n_head) {
err = "частичный RoPE (rope.dimension_count = " + std::to_string(rope_dim) +
" != head_dim = " + std::to_string(a.cfg.n_embd / a.cfg.n_head) + ") не поддерживается";
return false;
}
const int64_t kl = g.get_int("llama.attention.key_length", -1);
const int64_t vl = g.get_int("llama.attention.value_length", -1);
if (a.cfg.n_head > 0 && ((kl > 0 && kl != a.cfg.n_embd / a.cfg.n_head) ||
(vl > 0 && vl != a.cfg.n_embd / a.cfg.n_head))) {
err = "key_length/value_length != head_dim — не поддерживается";
return false;
}
for (const char* b : {"attn_q.bias", "attn_k.bias", "attn_v.bias", "attn_output.bias"}) {
if (g.find_tensor(("blk.0." + std::string(b)).c_str())) {
err = std::string("модели с bias'ами attention (найден blk.0.") + b +
") не поддерживаются (например, Qwen/GPT-NeoX — это не «чистая» LLaMA)";
return false;
}
}
a.cfg.n_vocab_out = g.find_tensor("output.weight") ? -1 : 0;
}
// vocab_size — по тензору эмбеддингов (источник истины для логитов)
const GgufTensorInfo* emb = g.find_tensor("token_embd.weight");
if (!emb) { err = "в GGUF нет тензора token_embd.weight"; return false; }
if (emb->dims.size() != 2) { err = "token_embd.weight должен быть 2-мерным"; return false; }
a.cfg.vocab_size = (int)emb->dims[1];
a.tied = (a.cfg.n_vocab_out == 0 || a.cfg.n_vocab_out == a.cfg.vocab_size);
a.has_output_weight = g.find_tensor("output.weight") != nullptr;
if (!a.cfg.valid(err)) return false;
if (!a.tied) {
const GgufTensorInfo* ow = g.find_tensor("output.weight");
if (ow && (ow->dims.size() != 2 || (int)ow->dims[1] != a.cfg.vocab_out())) {
err = "output.weight имеет " + std::to_string(ow->dims.size() ? ow->dims.back() : 0) +
" строк, ожидалось " + std::to_string(a.cfg.vocab_out()) +
" (Xenith не поддерживает vocab_size != output_size)";
return false;
}
}
// --- словарь ---
g.get_str_array("tokenizer.ggml.tokens", a.tokens);
g.get_str_array("tokenizer.ggml.merges", a.merges);
g.get_i32_array("tokenizer.ggml.token_type", a.token_types);
a.tokenizer_model = g.get_str("tokenizer.ggml.model", "");
a.bos = (int)g.get_int("tokenizer.ggml.bos_token_id", 1);
a.eos = (int)g.get_int("tokenizer.ggml.eos_token_id", 2);
a.unk = (int)g.get_int("tokenizer.ggml.unknown_token_id", 0);
a.encode_adds_bos = g.get_bool("tokenizer.ggml.add_bos_token",
g.get_bool("xenith.tokenizer.add_bos", true));
if (a.arch == "xenith")
a.encode_appends_eos = g.get_bool("xenith.tokenizer.append_eos", true);
else
a.encode_appends_eos = false; // импорту eos в промпте мешает
if (a.arch == "xenith") {
a.user = (int)g.get_int("xenith.tokenizer.user_id", 3);
a.asst = (int)g.get_int("xenith.tokenizer.assistant_id", 4);
a.nl = (int)g.get_int("xenith.tokenizer.newline_id", 5);
a.bpe_kind = (BpeKind)g.get_int("xenith.tokenizer.bpe_kind", 0);
} else {
a.user = a.asst = -1;
a.nl = -1;
if (!bpe_kind_from_tokenizer_model(a.tokenizer_model, a.bpe_kind)) {
a.bpe_kind = a.merges.empty() ? BpeKind::None : BpeKind::SentencePiece;
if (!a.tokenizer_model.empty()) {
engine_warn("неизвестный tokenizer.ggml.model '" + a.tokenizer_model +
"' — словарь трактуется как " +
(a.bpe_kind == BpeKind::None ? "атомарный (без BPE)" : "SentencePiece-BPE"));
}
}
}
if (a.tokens.empty()) {
err = "в GGUF нет tokenizer.ggml.tokens — словарь отсутствует";
return false;
}
return true;
}
// Найти id токена "\n" (для импорта llama).
int find_newline_id(const std::vector<std::string>& toks) {
for (size_t i = 0; i < toks.size(); ++i)
if (toks[i] == "\n") return (int)i;
return -1;
}
// Проверить, что все нужные тензоры есть и читаемы (без чтения данных).
bool check_tensors_present(const GgufFile& g, const ArchConfig& a, std::string& err) {
auto need = [&](const std::string& name) -> bool {
const GgufTensorInfo* ti = g.find_tensor(name);
if (!ti) { err = "в GGUF нет тензора '" + name + "'"; return false; }
if (!ti->supported()) {
char b[160];
snprintf(b, sizeof b, "тензор '%s': тип ggml id=%u не поддерживается Xenith",
name.c_str(), ti->raw_type);
err = b;
return false;
}
return true;
};
if (!need("token_embd.weight")) return false;
if (!a.tied && !need("output.weight")) return false;
if (!need("output_norm.weight")) return false;
const int d = a.cfg.n_embd, ffn = a.cfg.ffn();
const int hd = a.cfg.n_head > 0 ? d / a.cfg.n_head : d;
const int kv_out = (a.arch == "llama" && a.n_kv_head > 0) ? a.n_kv_head * hd : d;
struct Shape { const char* suffix; int r, c; bool transpose; };
for (int L = 0; L < a.cfg.n_layer; ++L) {
const Shape shapes[] = {
{"attn_q.weight", d, d, true },
{"attn_k.weight", d, kv_out, true },
{"attn_v.weight", d, kv_out, true },
{"attn_output.weight", d, d, true },
{"attn_norm.weight", 1, d, false},
{"ffn_norm.weight", 1, d, false},
{"ffn_gate.weight", d, ffn, true },
{"ffn_down.weight", ffn, d, true },
{"ffn_up.weight", d, ffn, true },
};
for (const Shape& s : shapes) {
const std::string name = blk_name(L, s.suffix);
if (!need(name)) return false;
const GgufTensorInfo* ti = g.find_tensor(name);
// ожидаемые dims: {in, out} для матриц (transposed-хранение), {d} для норм
if (s.transpose) {
if (ti->dims.size() != 2 || (int)ti->dims[0] != s.r || (int)ti->dims[1] != s.c) {
err = "тензор '" + name + "': dims не соответствуют конфигурации";
return false;
}
} else {
const int64_t ne = ti->n_elems();
if (ne != d) { err = "тензор '" + name + "': ожидалось " + std::to_string(d) + " весов"; return false; }
}
}
}
return true;
}
// Импорт матрицы из row-major раскладки [out][in] (ggml и HF Linear совпадают)
// в Xenith-тензор [in][out].
// expand_hd > 0 : источник — K/V-матрица GQA [kv_out = n_kv*hd][in]; каждая
// q-голова h получает kv-голову h/group (group = n_head/n_kv).
// rope_permute : выходы Q/K переставляются из rotate-half (llama/HF) в
// интерлив-пары Xenith (те же частоты, другая упаковка).
bool import_weights_flat_impl(const float* data, int64_t n, Tensor& dst,
int expand_hd, bool rope_permute, int n_head,
std::string& err) {
const int64_t R = dst.R(), C = dst.C();
if (expand_hd > 0) {
const int64_t hd = expand_hd;
const int64_t kv_out = n / R;
if (hd <= 0 || kv_out <= 0 || kv_out % hd != 0 || C % hd != 0 ||
n != R * kv_out || (C / hd) % (kv_out / hd) != 0) {
err = "не удалось развернуть GQA (" + std::to_string(n) + " весов, dst " +
std::to_string(R) + "x" + std::to_string(C) + ", hd " + std::to_string(hd) + ")";
return false;
}
const int64_t n_head_l = C / hd, n_kv = kv_out / hd;
const int64_t group = n_head_l / n_kv;
float* p = dst.ptr();
for (int64_t h = 0; h < n_head_l; ++h) {
const int64_t src_row0 = (h / group) * hd;
for (int64_t r = 0; r < hd; ++r) {
const int64_t o = h * hd + r;
const float* srow = data + (size_t)(src_row0 + r) * (size_t)R;
for (int64_t ii = 0; ii < R; ++ii)
p[(size_t)ii * (size_t)C + (size_t)o] = srow[ii];
}
}
} else {
if (n != R * C) {
err = "размер " + std::to_string(n) + ", ожидалось " + std::to_string(R * C);
return false;
}
float* p = dst.ptr();
for (int64_t o = 0; o < C; ++o)
for (int64_t ii = 0; ii < R; ++ii)
p[(size_t)ii * (size_t)C + (size_t)o] = data[(size_t)o * (size_t)R + (size_t)ii];
}
if (rope_permute)
rope_permute_xenith(dst.ptr(), R, C, n_head > 0 ? n_head : 1, /*to_xenith=*/true);
return true;
}
// Загрузить один тензор из GGUF в Tensor (dims/тип проверяются вызывающим).
bool load_tensor_from_gguf(const GgufFile& g, const std::string& name,
Tensor& dst, bool transpose, std::string& err,
int expand_kv = 0, bool rope_permute = false, int n_head = 1) {
const GgufTensorInfo* ti = g.find_tensor(name);
if (!ti) { err = "в GGUF нет тензора '" + name + "'"; return false; }
if (!ti->supported()) { err = "тензор '" + name + "': неподдерживаемый тип ggml id=" +
std::to_string(ti->raw_type); return false; }
if (!transpose && expand_kv == 0) {
// без транспозиции — декодируем ПРЯМО в тензор (без копии размером с
// тензор: для token_embd больших моделей это сотни МБ пика)
if ((int64_t)dst.n() != ti->n_elems()) {
err = "тензор '" + name + "': размер " + std::to_string(ti->n_elems()) +
", ожидалось " + std::to_string(dst.n());
return false;
}
if (!g.read_tensor_f32_into(*ti, dst.ptr(), dst.n(), err)) {
err = "тензор '" + name + "': " + err;
return false;
}
return true;
}
std::vector<float> f32;
if (!g.read_tensor_f32(*ti, f32, err)) { err = "тензор '" + name + "': " + err; return false; }
if (!import_weights_flat_impl(f32.data(), (int64_t)f32.size(), dst,
expand_kv, rope_permute, n_head, err)) {
err = "тензор '" + name + "': " + err;
return false;
}
return true;
}
} // namespace
bool import_weights_flat(const float* data, int64_t n, Tensor& dst,
int expand_hd, bool rope_permute, int n_head,
std::string& err) {
return import_weights_flat_impl(data, n, dst, expand_hd, rope_permute, n_head, err);
}
// ===========================================================================
// Экспорт: Checkpoint → GGUF
// ===========================================================================
bool gguf_save_checkpoint(const std::string& path,
const Params& p, const Tokenizer& tok,
int step, float loss, uint64_t seed,
const GgufSaveOptions& opt, std::string& err) {
materialize_params(p);
const Config& c = p.cfg;
const int ffn = c.ffn();
GgufBuilder b(opt.alignment ? opt.alignment : 32);
b.set_str("general.architecture", "xenith");
{
std::string name = opt.name;
if (name.empty()) {
name = std::filesystem::path(path).stem().string();
if (name.empty()) name = "xenith-model";
}
b.set_str("general.name", name);
}
b.set_u32("general.file_type", (uint32_t)opt.quant);
b.set_u32("xenith.context_length", (uint32_t)c.block_size);
b.set_u32("xenith.embedding_length", (uint32_t)c.n_embd);
b.set_u32("xenith.block_count", (uint32_t)c.n_layer);
b.set_u32("xenith.feed_forward_length", (uint32_t)ffn);
b.set_u32("xenith.attention.head_count", (uint32_t)c.n_head);
b.set_f32("xenith.rope.freq_base", (float)c.rope_base);
b.set_f32("xenith.attention.layer_norm_rms_epsilon", c.rms_eps);
b.set_f32("xenith.init_std", c.init_std);
b.set_i32("xenith.vocab_out", c.n_vocab_out);
b.set_i32("xenith.training_step", step);
b.set_f32("xenith.training_loss", loss);
b.set_u64("xenith.seed", seed);
// --- токенайзер ---
b.set_str("tokenizer.ggml.model",
tok.bpe == BpeKind::SentencePiece ? "llama" :
tok.bpe == BpeKind::ByteLevel ? "gpt2" : "xenith");
b.set_arr_str("tokenizer.ggml.tokens", tok.id2tok);
{
std::vector<int32_t> types(tok.id2tok.size(), 1); // 1 = normal
auto mark = [&](int id) { if (id >= 0 && id < (int)types.size()) types[id] = 3; }; // 3 = control
mark(tok.unk); mark(tok.bos); mark(tok.eos); mark(tok.user); mark(tok.asst);
if (tok.bpe == BpeKind::None) mark(tok.nl);
b.set_arr_i32("tokenizer.ggml.token_type", types);
}
if (!tok.merges.empty()) b.set_arr_str("tokenizer.ggml.merges", tok.merges);
if (tok.bos >= 0) b.set_u32("tokenizer.ggml.bos_token_id", (uint32_t)tok.bos);
if (tok.eos >= 0) b.set_u32("tokenizer.ggml.eos_token_id", (uint32_t)tok.eos);
if (tok.unk >= 0) b.set_u32("tokenizer.ggml.unknown_token_id", (uint32_t)tok.unk);
b.set_i32("xenith.tokenizer.user_id", tok.user);
b.set_i32("xenith.tokenizer.assistant_id", tok.asst);
b.set_i32("xenith.tokenizer.newline_id", tok.nl);
b.set_i32("xenith.tokenizer.bpe_kind", (int32_t)tok.bpe);
// Q/K лежат в ggml-раскладке rotate-half (см. rope_permute_xenith)
b.set_str("xenith.rope_layout", "half");
b.set_bool("tokenizer.ggml.add_bos_token", tok.encode_adds_bos);
b.set_bool("xenith.tokenizer.append_eos", tok.encode_appends_eos);
// --- тензоры ---
std::vector<float> buf;
std::map<std::string, std::string> fallback_notes; // тип → замена (для лога)
auto add = [&](const std::string& name, const Tensor& t, bool transpose, QType qt) -> bool {
if (transpose) transpose_to_ggml(t, buf);
else plain_copy(t, buf);
// ggml-порядок dims: dims[0] = ne0 = НЕПРЕРЫВНАЯ ось.
// - транспонируемые матрицы: после transpose_to_ggml строка = выходной
// признак, ne0 = t.R() (вход) → dims {R, C};
// - эмбеддинги [V][d] уже лежат в ggml-раскладке: ne0 = d = t.C() → {C, R};
// - нормы (1, d) → одномерные {d}.
std::vector<uint64_t> dims;
int64_t ne0;
if (transpose) { dims = { (uint64_t)t.R(), (uint64_t)t.C() }; ne0 = t.R(); }
else if (t.R() == 1) { dims = { (uint64_t)t.C() }; ne0 = t.C(); }
else { dims = { (uint64_t)t.C(), (uint64_t)t.R() }; ne0 = t.C(); }
// ggml требует ne0 % block_size == 0; иначе — откат типа как в llama.cpp
QType eff = qt;
if (!qtype_fallback_for_row(qt, ne0, eff)) {
err = "тензор '" + name + "': строка из " + std::to_string(ne0) +
" весов несовместима с " + qtype_name(qt) +
" (нет определённого отката, как и в llama.cpp) — выберите другой тип";
return false;
}
if (eff != qt) fallback_notes[qtype_name(qt)] = qtype_name(eff);
if (!b.add_tensor(name, dims, buf.data(), (int64_t)t.n(), eff, err)) {
err = "тензор '" + name + "': " + err;
return false;
}
return true;
};
// Q/K при экспорте переводим в ggml-раскладку rotate-half, чтобы файл был
// семантически совместим с экосистемой ggml (и точно круговался обратно).
auto add_rope = [&](const std::string& name, const Tensor& t, QType qt) -> bool {
std::vector<float> xb(t.ptr(), t.ptr() + t.n()); // копия [R][C]
rope_permute_xenith(xb.data(), t.R(), t.C(), c.n_head, /*to_xenith=*/false);
const int64_t R = t.R(), C = t.C();
buf.assign((size_t)R * (size_t)C, 0.0f);
for (int64_t o = 0; o < C; ++o) // транспозиция в ggml [out][in]
for (int64_t i2 = 0; i2 < R; ++i2)
buf[(size_t)o * (size_t)R + (size_t)i2] = xb[(size_t)i2 * (size_t)C + (size_t)o];
std::vector<uint64_t> dims = { (uint64_t)R, (uint64_t)C };
if (!b.add_tensor(name, dims, buf.data(), (int64_t)t.n(), qt, err)) {
err = "тензор '" + name + "': " + err;
return false;
}
return true;
};
const QType norms = opt.norms_f32 ? QType::F32 : opt.quant;
if (!add("token_embd.weight", p.wte, /*transpose=*/false, opt.emb_type)) return false;
if (!p.tied() && !add("output.weight", p.lm_head, false, opt.output_type)) return false;
for (int L = 0; L < c.n_layer; ++L) {
if (!add_rope(blk_name(L, "attn_q.weight"), p.wq[L], opt.quant)) return false;
if (!add_rope(blk_name(L, "attn_k.weight"), p.wk[L], opt.quant)) return false;
if (!add(blk_name(L, "attn_v.weight"), p.wv[L], true, opt.quant)) return false;
if (!add(blk_name(L, "attn_output.weight"), p.wo[L], true, opt.quant)) return false;
if (!add(blk_name(L, "attn_norm.weight"), p.rms_attn[L], false, norms)) return false;
if (!add(blk_name(L, "ffn_norm.weight"), p.rms_ffn[L], false, norms)) return false;
if (!add(blk_name(L, "ffn_gate.weight"), p.w1[L], true, opt.quant)) return false;
if (!add(blk_name(L, "ffn_down.weight"), p.w2[L], true, opt.quant)) return false;
if (!add(blk_name(L, "ffn_up.weight"), p.w3[L], true, opt.quant)) return false;
}
if (!add("output_norm.weight", p.rms_final, false, norms)) return false;
for (const auto& fb : fallback_notes) {
char wb[256];
snprintf(wb, sizeof wb,
"%s: строки тензоров не кратны блоку — заменён на %s (правило llama.cpp)",
fb.first.c_str(), fb.second.c_str());
engine_warn(wb);
}
if (!b.write(path, err)) return false;
return true;
}
// ===========================================================================
// Импорт: GGUF → Checkpoint
// ===========================================================================
bool gguf_load_checkpoint(const std::string& path, Checkpoint& ck, std::string& err,
const LoadOptions& opt) {
GgufFile g;
if (!g.open(path, err)) return false;
ArchConfig a;
if (!read_arch_config(g, a, err)) return false;
if (!check_tensors_present(g, a, err)) return false;
// --- контекст: внешние модели могут иметь context_length 128K; KV-кэш
// генерации растёт линейно, поэтому режем до opt.gguf_ctx_cap.
if (a.arch != "xenith" && opt.gguf_ctx_cap > 0 && a.cfg.block_size > opt.gguf_ctx_cap) {
char ib[256];
snprintf(ib, sizeof ib,
"контекст модели %d урезан до %d (KV-кэш); полностью — через "
"`Xenith convert ... --ctx N`", a.cfg.block_size, opt.gguf_ctx_cap);
engine_info(ib);
a.cfg.block_size = opt.gguf_ctx_cap;
}
// --- конфиг и тензоры ---
Config& c = ck.params.cfg = a.cfg;
const int d = c.n_embd, ffn = c.ffn();
ck.params.wte.resize(c.vocab_size, d);
if (!a.tied) ck.params.lm_head.resize(c.vocab_out(), d);
ck.params.wq.resize(c.n_layer, Tensor(d, d));
ck.params.wk.resize(c.n_layer, Tensor(d, d));
ck.params.wv.resize(c.n_layer, Tensor(d, d));
ck.params.wo.resize(c.n_layer, Tensor(d, d));
ck.params.rms_attn.resize(c.n_layer, Tensor(1, d));
ck.params.rms_ffn.resize(c.n_layer, Tensor(1, d));
ck.params.w1.resize(c.n_layer, Tensor(d, ffn));
ck.params.w2.resize(c.n_layer, Tensor(ffn, d));
ck.params.w3.resize(c.n_layer, Tensor(d, ffn));
ck.params.rms_final = Tensor(1, d);
const bool rope_half = (a.arch == "llama") ||
(g.get_str("xenith.rope_layout", "") == "half");
if (!load_tensor_from_gguf(g, "token_embd.weight", ck.params.wte, false, err)) return false;
if (!a.tied) {
if (!load_tensor_from_gguf(g, "output.weight", ck.params.lm_head, false, err)) return false;
}
if (!load_tensor_from_gguf(g, "output_norm.weight", ck.params.rms_final, false, err)) return false;
for (int L = 0; L < c.n_layer; ++L) {
const int expand = (a.arch == "llama" && a.n_kv_head > 0 && a.n_kv_head != a.cfg.n_head)
? c.head_dim() : 0; // = hd: развёртка блоками голов
// Q/K: ggml хранит их в раскладке rotate-half; при rope_half
// переставляем выходы в интерлив-пары Xenith (частоты те же).
// Экспорты Xenith ДО xenith.rope_layout лежали в interleave-виде — не трогаем.
if (!load_tensor_from_gguf(g, blk_name(L, "attn_q.weight"), ck.params.wq[L], true, err,
0, rope_half, c.n_head)) return false;
if (!load_tensor_from_gguf(g, blk_name(L, "attn_k.weight"), ck.params.wk[L], true, err,
expand, rope_half, c.n_head)) return false;
if (!load_tensor_from_gguf(g, blk_name(L, "attn_v.weight"), ck.params.wv[L], true, err, expand)) return false;
if (!load_tensor_from_gguf(g, blk_name(L, "attn_output.weight"), ck.params.wo[L], true, err)) return false;
if (!load_tensor_from_gguf(g, blk_name(L, "attn_norm.weight"), ck.params.rms_attn[L], false, err)) return false;
if (!load_tensor_from_gguf(g, blk_name(L, "ffn_norm.weight"), ck.params.rms_ffn[L], false, err)) return false;
if (!load_tensor_from_gguf(g, blk_name(L, "ffn_gate.weight"), ck.params.w1[L], true, err)) return false;
if (!load_tensor_from_gguf(g, blk_name(L, "ffn_down.weight"), ck.params.w2[L], true, err)) return false;
if (!load_tensor_from_gguf(g, blk_name(L, "ffn_up.weight"), ck.params.w3[L], true, err)) return false;
}
// --- токенайзер ---
Tokenizer& tk = ck.tok;
tk.id2tok = a.tokens;
if ((int)tk.id2tok.size() > c.vocab_size) {
char ib[192];
snprintf(ib, sizeof ib, "словарь GGUF (%zu) больше матрицы эмбеддингов (%d) — обрезаю",
tk.id2tok.size(), c.vocab_size);
engine_warn(ib);
tk.id2tok.resize(c.vocab_size);
}
while ((int)tk.id2tok.size() < c.vocab_size) tk.id2tok.push_back(""); // «дырки» vocab
tk.bpe = a.bpe_kind;
tk.merges = a.merges;
tk.encode_adds_bos = a.encode_adds_bos;
tk.encode_appends_eos = a.encode_appends_eos;
tk.idx_.reset();
tk.unk = (a.unk >= 0 && a.unk < (int)tk.id2tok.size()) ? a.unk : 0;
tk.bos = (a.bos >= 0 && a.bos < (int)tk.id2tok.size()) ? a.bos : 1;
tk.eos = (a.eos >= 0 && a.eos < (int)tk.id2tok.size()) ? a.eos : 2;
tk.user = a.user;
tk.asst = a.asst;
tk.nl = (a.nl >= 0) ? a.nl : find_newline_id(tk.id2tok);
if (tk.user >= (int)tk.id2tok.size()) tk.user = -1;
if (tk.asst >= (int)tk.id2tok.size()) tk.asst = -1;
ck.step = a.step;
ck.loss = a.loss;
ck.seed = a.seed;
if (opt.alloc_grads) ck.params.alloc_grads();
else ck.params.mark_grads_lazy();
// m/v в GGUF не хранятся — opt.want_optimizer игнорируется.
char ib[320];
snprintf(ib, sizeof ib, "импортирован GGUF (v%u, arch=%s): %d слоёв, d=%d, словарь %d",
g.version(), a.arch.c_str(), c.n_layer, d, c.vocab_size);
engine_info(ib);
if (a.arch == "llama" && a.n_kv_head > 0 && a.n_kv_head != c.n_head) {
snprintf(ib, sizeof ib,
"GQA: %d kv-голов развёрнуто в %d (веса K/V расширены; инференс точный, "
"дообучение трактует копии как независимые головы)", a.n_kv_head, c.n_head);
engine_info(ib);
}
if (a.arch != "xenith" && tk.user < 0)
engine_info("в словаре нет маркеров <user>/<assistant> — chat и fine-tune недоступны, "
"gen/ollama работают");
return true;
}
// ===========================================================================
// Probe / dump
// ===========================================================================
bool gguf_probe(const std::string& path, ModelFileInfo& info) {
GgufFile g;
if (!g.open(path, info.error)) return false;
info.is_gguf = true;
info.file_bytes = g.file_bytes();
info.format_version = g.version();
// сводка квантований
std::map<std::string, int> by_type;
for (const GgufTensorInfo& t : g.tensors()) {
const QTypeInfo* qi = qtype_info_by_id(t.raw_type);
by_type[qi ? qi->name : ("id" + std::to_string(t.raw_type))]++;
}
{
std::vector<std::pair<std::string,int>> items(by_type.begin(), by_type.end());
std::sort(items.begin(), items.end(),
[](const auto& a, const auto& b) { return a.second > b.second; });
std::string s;
for (const auto& it : items) {
if (!s.empty()) s += ' ';
s += it.first + "\xC3\x97" + std::to_string(it.second); // ×N
}
info.quant_summary = s;
}
ArchConfig a;
std::string cerr;
if (read_arch_config(g, a, cerr)) {
info.arch = a.arch;
info.cfg = a.cfg;
info.step = a.step;
info.loss = a.loss;
info.seed = a.seed;
info.vocab_entries = (int)a.tokens.size();
info.has_optimizer = false;
info.mappable = check_tensors_present(g, a, cerr);
if (!info.mappable) info.error = cerr;
info.ok = info.mappable;
} else {
info.arch = g.get_str("general.architecture", "?");
info.mappable = false;
info.ok = false;
info.error = cerr;
// файл сам по себе не битый — для info этого достаточно
}
return info.ok;
}
std::string gguf_dump(const std::string& path, std::string& err) {
GgufFile g;
if (!g.open(path, err)) return {};
std::string out;
char b[512];
snprintf(b, sizeof b, "контейнер : GGUF v%u, alignment %llu, %.2f МБ\n",
g.version(), (unsigned long long)g.alignment(),
(double)g.file_bytes() / 1048576.0);
out += b;
snprintf(b, sizeof b, "метаданные : %zu записей\n", g.kv().size());
out += b;
for (const auto& kv : g.kv()) {
std::string v = kv.second.to_display();
if (v.size() > 110) v = v.substr(0, 107) + "...";
out += " " + kv.first + " = " + v + "\n";
}
snprintf(b, sizeof b, "тензоры : %zu\n", g.tensors().size());
out += b;
double total_params = 0;
double total_bytes = 0;
double total_bits = 0;
for (const GgufTensorInfo& t : g.tensors()) {
const QTypeInfo* qi = qtype_info_by_id(t.raw_type);
std::string dims = "[";
for (size_t i = 0; i < t.dims.size(); ++i) {
if (i) dims += ", ";
dims += std::to_string(t.dims[i]);
}
dims += "]";
const double n = (double)t.n_elems();
const double bytes = qi ? (double)t.n_bytes() : 0;
total_params += n;
total_bytes += bytes;
if (qi) total_bits += n * qi->bpw();
const std::string tname = qi ? qi->name : ("id" + std::to_string(t.raw_type));
snprintf(b, sizeof b, " %-38s %-18s %-9s %6.3f bpw %9.2f КБ%s\n",
t.name.c_str(), dims.c_str(), tname.c_str(),
qi ? qi->bpw() : 0.0, bytes / 1024.0,
qi ? "" : " (не поддерживается Xenith)");
out += b;
}
if (total_params > 0) {
snprintf(b, sizeof b, "итого : %.2f М параметров, %.2f МБ, среднее %.3f bpw\n",
total_params / 1048576.0, total_bytes / 1048576.0,
total_bits / std::max(1.0, total_params));
out += b;
}
ArchConfig a;
std::string cerr;
if (read_arch_config(g, a, cerr) && check_tensors_present(g, a, cerr)) {
out += "маппинг : архитектура '" + a.arch + "' поддерживается — модель можно "
"загрузить (gen/chat/convert)\n";
snprintf(b, sizeof b,
"конфиг : слоёв %d, голов %d, embd %d, ffn %d, словарь %d, контекст %d, rope %d, tied %s\n",
a.cfg.n_layer, a.cfg.n_head, a.cfg.n_embd, a.cfg.ffn(),
a.cfg.vocab_size, a.cfg.block_size, a.cfg.rope_base, a.tied ? "да" : "нет");
out += b;
out += std::string("токенайзер : ") + bpe_kind_name(a.bpe_kind) +
", токенов " + std::to_string(a.tokens.size()) +
", слияний " + std::to_string(a.merges.size()) + "\n";
} else if (!cerr.empty()) {
out += "маппинг : НЕ поддерживается — " + cerr + "\n";
}
return out;
}
// ===========================================================================
// Ре-квантование GGUF → GGUF (на уровне контейнера, архитектура не важна)
// ===========================================================================
bool gguf_requantize(const std::string& in, const std::string& out_path,
QType quant, int emb_id, int output_id, std::string& err) {
GgufFile g;
if (!g.open(in, err)) return false;
GgufBuilder b((uint32_t)g.alignment());
for (const auto& kv : g.kv()) {
if (kv.first == "general.file_type") continue; // перезапишем
b.set_value(kv.first, kv.second);
}
b.set_u32("general.file_type", (uint32_t)quant);
size_t copied = 0, requantized = 0;
for (const GgufTensorInfo& t : g.tensors()) {
if (!t.supported()) {
err = "тензор '" + t.name + "': тип ggml id=" + std::to_string(t.raw_type) +
" не поддерживается — ре-квантование невозможно";
return false;
}
QType target = quant;
const bool is_norm = ends_with(t.name, "_norm.weight");
if (is_norm) {
target = QType::F32; // нормы — всегда f32 (llama.cpp)
} else if (t.name == "token_embd.weight") {
if (emb_id == -1) target = t.type; // оставить как есть
else if (emb_id >= 0) target = (QType)(uint32_t)emb_id;
} else if (t.name == "output.weight") {
if (output_id == -1) target = t.type;
else if (output_id >= 0) target = (QType)(uint32_t)output_id;
}
// совместимость формы: ne0 должно делиться на блок типа
const int64_t ne0 = t.dims.empty() ? 0 : (int64_t)t.dims[0];
QType eff = target;
if (!qtype_fallback_for_row(target, ne0, eff)) {
err = "тензор '" + t.name + "': строка " + std::to_string(ne0) +
" несовместима с " + qtype_name(target) + " (отката нет) — выберите другой тип";
return false;
}
if (eff != target) {
char wb[256];
snprintf(wb, sizeof wb, "%s: %s -> %s (строка %lld не кратна блоку)",
t.name.c_str(), qtype_name(target), qtype_name(eff), (long long)ne0);
engine_warn(wb);
target = eff;
}
if (target == t.type) {
std::vector<uint8_t> raw;
if (!g.read_tensor_raw(t, raw, err)) return false;
b.add_tensor_raw(t.name, t.dims, t.type, std::move(raw), err);
++copied;
} else {
std::vector<float> f32;
if (!g.read_tensor_f32(t, f32, err)) return false;
if (!b.add_tensor(t.name, t.dims, f32.data(), (int64_t)f32.size(), target, err))
return false;
++requantized;
}
}
if (!b.write(out_path, err)) return false;
char ib[256];
snprintf(ib, sizeof ib, "GGUF: %zu тензоров переквантовано в %s, %zu скопировано как есть",
requantized, qtype_name(quant), copied);
engine_info(ib);
return true;
}
// ===========================================================================
// Универсальная конвертация
// ===========================================================================
bool model_convert(const std::string& in, const std::string& out,
const ConvertOptions& opt, std::string& err) {
const bool in_gguf = GgufFile::is_gguf_path(in);
const std::string in_ext = lower_str(std::filesystem::path(in).extension().string());
const bool in_st = !in_gguf && (in_ext == ".safetensors" || SafetensorsFile::is_safetensors_path(in));
const std::string out_ext = lower_str(std::filesystem::path(out).extension().string());
const bool out_gguf = (out_ext == ".gguf");
const bool out_xnh = (out_ext == ".xnh");
const bool out_st = (out_ext == ".safetensors");
if (!out_gguf && !out_xnh && !out_st) {
err = "непонятное расширение выхода '" + out_ext + "' (ожидалось .gguf, .xnh или .safetensors)";
return false;
}
// --- safetensors на входе: грузим в Checkpoint, дальше как обычно ---
if (in_st) {
Checkpoint ck;
LoadOptions lo;
lo.alloc_grads = false;
lo.want_optimizer = false;
lo.gguf_ctx_cap = 0; // конвертация сохраняет контекст
if (!st_load_checkpoint(in, ck, err, lo)) return false;
if (opt.ctx_override > 0) ck.params.cfg.block_size = opt.ctx_override;
if (out_xnh)
return save_checkpoint(out, ck.params, ck.tok, ck.step, ck.loss, ck.seed, err);
if (out_st) {
err = "safetensors → safetensors не имеет смысла (скопируйте файл)";
return false;
}
// → GGUF
GgufSaveOptions so;
so.quant = opt.quant;
so.emb_type = opt.emb_set ? opt.emb_type : opt.quant;
so.output_type = opt.output_set ? opt.output_type : opt.quant;
so.norms_f32 = opt.norms_f32;
so.name = opt.name;
so.alignment = opt.alignment;
return gguf_save_checkpoint(out, ck.params, ck.tok, ck.step, ck.loss, ck.seed, so, err);
}
// --- safetensors на выходе ---
if (out_st) {
Checkpoint ck;
LoadOptions lo;
lo.alloc_grads = false;
lo.want_optimizer = false;
if (in_gguf) {
lo.gguf_ctx_cap = 0;
if (!gguf_load_checkpoint(in, ck, err, lo)) return false;
} else {
if (!load_checkpoint(in, ck, err, lo)) return false;
}
if (opt.ctx_override > 0) ck.params.cfg.block_size = opt.ctx_override;
return st_save_checkpoint(out, ck.params, ck.tok, ck.step, ck.loss, ck.seed,
opt.st_dtype, err);
}
if (!in_gguf && out_gguf) {
// .xnh → .gguf
Checkpoint ck;
LoadOptions lo;
lo.alloc_grads = false;
lo.want_optimizer = false;
if (!load_checkpoint(in, ck, err, lo)) return false;
if (opt.ctx_override > 0) ck.params.cfg.block_size = opt.ctx_override;
GgufSaveOptions so;
so.quant = opt.quant;
so.emb_type = opt.emb_set ? opt.emb_type : opt.quant;
so.output_type = opt.output_set ? opt.output_type : opt.quant;
so.norms_f32 = opt.norms_f32;
so.name = opt.name;
so.alignment = opt.alignment;
return gguf_save_checkpoint(out, ck.params, ck.tok, ck.step, ck.loss, ck.seed, so, err);
}
if (in_gguf && out_xnh) {
// .gguf → .xnh (деквантование в fp32)
Checkpoint ck;
LoadOptions lo;
lo.alloc_grads = false;
lo.want_optimizer = false;
lo.gguf_ctx_cap = 0; // конвертация сохраняет контекст как есть
if (!gguf_load_checkpoint(in, ck, err, lo)) return false;
if (opt.ctx_override > 0) ck.params.cfg.block_size = opt.ctx_override;
return save_checkpoint(out, ck.params, ck.tok, ck.step, ck.loss, ck.seed, err);
}
if (in_gguf && out_gguf) {
// .gguf → .gguf (ре-квантование)
const int emb_id = opt.emb_set ? (int)opt.emb_type : -2;
const int out_id = opt.output_set ? (int)opt.output_type : -2;
return gguf_requantize(in, out, opt.quant, emb_id, out_id, err);
}
err = "конвертация .xnh → .xnh не нужна: .xnh всегда хранит fp32 "
"(квантование живёт в GGUF/safetensors — конвертируйте в .gguf)";
return false;
}
} // namespace xt