1528 lines
75 KiB
C++
1528 lines
75 KiB
C++
#include "xenith/core/checkpoint.h"
|
||
#include "xenith/core/gguf.h"
|
||
#include "xenith/core/gguf_model.h"
|
||
#include "xenith/core/safetensors.h"
|
||
#include "xenith/core/agent.h"
|
||
#include "xenith/core/multimodal.h"
|
||
#include "xenith/core/quant.h"
|
||
#include "xenith/core/generate.h"
|
||
#include "xenith/core/train.h"
|
||
#include "xenith/core/gradcheck.h"
|
||
#include "xenith/core/dataset.h"
|
||
#include "xenith/core/config.h"
|
||
#include "xenith/core/update.h"
|
||
#include "xenith/core/http_client.h"
|
||
#include "xenith/backend/backend.h"
|
||
#include "xenith/ui/ui.h"
|
||
#include "xenith/ollama_api/handler.h"
|
||
#include "xenith/libs/json-3.12.0/nlohmann/json.hpp"
|
||
#include <cstdio>
|
||
#include <functional>
|
||
#include "help.h"
|
||
#include <cctype>
|
||
#include <cstdlib>
|
||
#include <algorithm>
|
||
#include <filesystem>
|
||
#include <string>
|
||
#include <vector>
|
||
#include <map>
|
||
#include <fstream>
|
||
#include <iostream>
|
||
#include <sstream>
|
||
|
||
#include "xenith/core/platform.h"
|
||
|
||
#ifdef _WIN32
|
||
# ifndef WIN32_LEAN_AND_MEAN
|
||
# define WIN32_LEAN_AND_MEAN
|
||
# endif
|
||
# ifndef NOMINMAX
|
||
# define NOMINMAX
|
||
# endif
|
||
# include <windows.h>
|
||
# include <shellapi.h>
|
||
#endif
|
||
|
||
namespace fs = std::filesystem;
|
||
// Объявление class filesystem_error внутри namespace std::filesystem::__cxx11
|
||
// убрано: добавлять объявления в std формально запрещено (UB), и оно здесь
|
||
// всё равно не использовалось.
|
||
|
||
using namespace xt;
|
||
|
||
|
||
|
||
static std::string read_all(const std::string& p, bool& ok) {
|
||
std::ifstream f(path_from_utf8(p), std::ios::binary);
|
||
if (!f) { ok = false; return {}; }
|
||
std::ostringstream ss; ss << f.rdbuf(); ok = true; return ss.str();
|
||
}
|
||
|
||
|
||
// Достаёт все строковые значения полей content/value/text из JSON-датасета
|
||
// диалогов. Используется командой new --from-json, чтобы словарь строился по
|
||
// текстам реплик, а не по ключам JSON.
|
||
static std::string extract_json_texts(const std::string& json_text, std::string& err) {
|
||
nlohmann::json j;
|
||
try { j = nlohmann::json::parse(json_text); }
|
||
catch (const std::exception& e) { err = std::string("ошибка JSON: ") + e.what(); return {}; }
|
||
|
||
std::ostringstream out;
|
||
size_t n = 0;
|
||
std::function<void(const nlohmann::json&)> walk = [&](const nlohmann::json& node) {
|
||
if (node.is_object()) {
|
||
for (const char* key : {"content", "value", "text"}) {
|
||
auto it = node.find(key);
|
||
if (it != node.end() && it->is_string()) {
|
||
const std::string v = it->get<std::string>();
|
||
if (!v.empty()) { out << v << "\n"; ++n; }
|
||
}
|
||
}
|
||
for (auto it = node.begin(); it != node.end(); ++it) walk(it.value());
|
||
} else if (node.is_array()) {
|
||
for (const auto& e : node) walk(e);
|
||
}
|
||
};
|
||
walk(j);
|
||
if (n == 0) err = "в JSON не найдено ни одного поля content/value/text";
|
||
return out.str();
|
||
}
|
||
|
||
static void mkdirs(const std::string& path) {
|
||
// std::filesystem вместо ручного цикла по компонентам с ::mkdir(0755):
|
||
// портируемо (Windows включительно) и не требует <sys/stat.h>.
|
||
if (path.empty()) return;
|
||
std::error_code ec;
|
||
fs::create_directories(path_from_utf8(path), ec);
|
||
}
|
||
|
||
|
||
struct Args {
|
||
std::map<std::string, std::string> kv;
|
||
std::vector<std::string> pos;
|
||
|
||
// Только эти флаги принимают значение. Раньше парсер считал значение
|
||
// обязательным для ЛЮБОГО --flag, поэтому `gen --mmap model.xnh "..."` съедал
|
||
// модель как значение --mmap, а булевы флаги ломали позиционные аргументы.
|
||
static bool takes_value(const std::string& k) {
|
||
static const char* const names[] = {
|
||
"accum", "alignment", "backend", "base", "batch", "beta1", "beta2",
|
||
"block", "ckpt-every", "clip", "conf", "config", "corpus", "ctx",
|
||
"data", "device", "dir", "ds-conf", "embd", "emb-type", "eps",
|
||
"experts", "ffn", "get", "heads", "host", "img", "init", "iters",
|
||
"label-smoothing", "layers", "log-every", "lr", "lr-min-frac",
|
||
"min-flops", "model", "n", "name", "optimizer", "out", "output-type",
|
||
"port", "prompt", "quant", "repeat-penalty", "rope", "seed",
|
||
"st-dtype", "steps", "system", "t", "tag", "temp", "threads",
|
||
"top-k", "top-k-gen", "top-p", "type", "val-every", "val-tokens",
|
||
"val-windows", "version", "vocab", "warmup", "wav", "wd"
|
||
};
|
||
for (const char* n : names) if (k == n) return true;
|
||
return false;
|
||
}
|
||
|
||
Args(int argc, char** argv, int from) {
|
||
for (int i = from; i < argc; ++i) {
|
||
std::string a = argv[i];
|
||
if (a.rfind("--", 0) == 0) {
|
||
std::string key = a.substr(2);
|
||
size_t eq = key.find('=');
|
||
if (eq != std::string::npos) {
|
||
kv[key.substr(0, eq)] = key.substr(eq + 1);
|
||
} else if (takes_value(key) && i + 1 < argc &&
|
||
std::string(argv[i + 1]).rfind("--", 0) != 0) {
|
||
kv[key] = argv[++i];
|
||
} else {
|
||
kv[key] = "1";
|
||
}
|
||
} else {
|
||
pos.push_back(a);
|
||
}
|
||
}
|
||
}
|
||
bool has(const char* k) const { return kv.count(k) > 0; }
|
||
std::string get(const char* k, const std::string& def = "") const {
|
||
auto it = kv.find(k);
|
||
return it == kv.end() ? def : it->second;
|
||
}
|
||
int geti(const char* k, int def) const {
|
||
auto it = kv.find(k);
|
||
return it == kv.end() ? def : std::atoi(it->second.c_str());
|
||
}
|
||
float getf(const char* k, float def) const {
|
||
auto it = kv.find(k);
|
||
return it == kv.end() ? def : (float)std::atof(it->second.c_str());
|
||
}
|
||
};
|
||
|
||
// Опции загрузки модели из CLI: --mmap (веса отображаются из файла без
|
||
// копирования в RAM), --mlock (держать страницы в памяти), --grads (выделить
|
||
// градиенты сразу). gen_only: команда не обучает — градиенты и состояние
|
||
// оптимизатора (m/v, это 2/3 файла) не читаются вообще (--resume возвращает m/v).
|
||
static LoadOptions load_opts(const Args& a, bool gen_only) {
|
||
LoadOptions o;
|
||
o.use_mmap = a.has("mmap");
|
||
o.mlock = a.has("mlock");
|
||
o.alloc_grads = !gen_only || a.has("grads");
|
||
o.want_optimizer = !gen_only || a.has("resume");
|
||
return o;
|
||
}
|
||
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Глобальные настройки и выбор бэкенда
|
||
// ---------------------------------------------------------------------------
|
||
static AppConfig g_cfg;
|
||
|
||
// Инициализация Vulkan по флагу --vulkan / runtime.backend.
|
||
// При любой неудаче честно сообщает причину и остаётся на CPU.
|
||
static void init_backend(const Args& a, const std::string& cmd) {
|
||
// Приоритет выбора бэкенда (старшие побеждают):
|
||
// 1. --vulkan / --gpu / --cpu / --no-vulkan
|
||
// 2. --backend cpu|vulkan
|
||
// 3. runtime.backend из config.yaml
|
||
// 4. vulkan.enabled из config.yaml
|
||
// Раньше значение из config.yaml применялось ПОСЛЕ флагов командной строки
|
||
// и молча затирало --vulkan: при штатном runtime.backend: cpu флаг --vulkan
|
||
// не делал вообще ничего и даже не предупреждал об этом.
|
||
const auto is_vk = [](const std::string& b) { return b == "vulkan" || b == "gpu" || b == "vk"; };
|
||
|
||
bool want_vk = g_cfg.vk.enabled; // 4
|
||
if (!g_cfg.runtime.backend.empty()) { // 3
|
||
if (is_vk(g_cfg.runtime.backend)) want_vk = true;
|
||
else if (g_cfg.runtime.backend == "cpu") want_vk = false;
|
||
}
|
||
if (a.has("backend")) { // 2
|
||
const std::string be = a.get("backend");
|
||
if (is_vk(be)) want_vk = true;
|
||
else if (be == "cpu") want_vk = false;
|
||
else fprintf(stderr, "%s неизвестный --backend '%s' (cpu|vulkan) — игнорирую\n",
|
||
sym::warn(), be.c_str());
|
||
}
|
||
if (a.has("vulkan") || a.has("gpu")) want_vk = true; // 1
|
||
if (a.has("cpu") || a.has("no-vulkan")) want_vk = false; // 1
|
||
|
||
if (!want_vk) { set_backend(nullptr); return; }
|
||
|
||
if (!vulkan_available()) {
|
||
fprintf(stderr, "%s Vulkan недоступен: сборка без -DXENITH_VULKAN=ON. Работаю на CPU.\n",
|
||
sym::warn());
|
||
return;
|
||
}
|
||
VulkanOptions vo;
|
||
vo.device_index = a.has("device") ? a.geti("device", g_cfg.vk.device_index) : g_cfg.vk.device_index;
|
||
vo.validation_layers = g_cfg.vk.validation_layers || a.has("vk-debug");
|
||
vo.min_gemm_flops = g_cfg.vk.min_gemm_flops;
|
||
// gradcheck обязан проверять именно GPU-ядра: со штатным порогом
|
||
// min_gemm_flops (262144) все GEMM и attention крошечной тестовой модели
|
||
// уходили на CPU-фолбэк, и «gradcheck --vulkan» не тестировал шейдеры
|
||
// gemm/attn ВООБЩЕ. Для gradcheck порог обнуляем (если не задан явно).
|
||
if (cmd == "gradcheck" && !a.has("min-flops")) vo.min_gemm_flops = 0;
|
||
if (a.has("min-flops")) vo.min_gemm_flops = a.geti("min-flops", vo.min_gemm_flops);
|
||
vo.workgroup_size = g_cfg.vk.workgroup_size;
|
||
vo.staging_mb = g_cfg.vk.staging_mb;
|
||
vo.persistent_buffers = g_cfg.vk.persistent_buffers;
|
||
vo.allow_integrated = g_cfg.vk.allow_integrated;
|
||
vo.fp16 = g_cfg.vk.fp16;
|
||
|
||
std::string err;
|
||
if (!vulkan_init(vo, err)) {
|
||
fprintf(stderr, "%s Vulkan не инициализирован: %s\n Работаю на CPU.\n",
|
||
sym::warn(), err.c_str());
|
||
set_backend(nullptr);
|
||
return;
|
||
}
|
||
printf("%s бэкенд: %s — %s\n", sym::check(), backend()->name(), backend()->describe().c_str());
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Прогресс-бар обучения
|
||
// ---------------------------------------------------------------------------
|
||
// Создаёт прогресс-бар и возвращает пару колбэков: тик прогресса и сообщения.
|
||
// Сообщения тренера (чекпоинт, val loss) обязаны идти через bar.note(), иначе
|
||
// они печатаются поверх открытой строки бара и вывод перемешивается.
|
||
static std::pair<ProgressFn, NoteFn> make_progress(ProgressBar& bar, int total, int log_every) {
|
||
bar.start(total > 0 ? total : 0, "");
|
||
if (log_every > 0)
|
||
printf("%sлог каждые %d шагов; прервать — Ctrl+C%s\n", col::grey(), log_every, col::reset());
|
||
NoteFn note = [&bar](const std::string& text) { bar.note(text); };
|
||
ProgressFn tick = [&bar](const TrainTick& t) {
|
||
TrainProgress p;
|
||
p.step = t.step;
|
||
p.total = t.total_steps;
|
||
p.loss = t.loss;
|
||
p.val_loss = t.val_loss;
|
||
p.lr = t.lr;
|
||
p.tokens_per_sec = t.tokens_per_sec;
|
||
p.elapsed_sec = t.elapsed_sec;
|
||
bar.tick(p);
|
||
if (t.is_last) bar.finish("");
|
||
};
|
||
return {tick, note};
|
||
}
|
||
|
||
static void finish_progress(ProgressBar& bar, const TrainStats& st, const std::string& out) {
|
||
bar.finish("");
|
||
if (st.step == 0) {
|
||
printf("%s%s%s обучение не выполнилось\n", col::red(), sym::cross(), col::reset());
|
||
return;
|
||
}
|
||
char buf[256];
|
||
snprintf(buf, sizeof buf, "готово: шаг %d, loss %.4f, ppl %.1f%s%s",
|
||
st.step, st.loss, std::exp(std::min(st.loss, 30.0f)),
|
||
out.empty() ? "" : " -> ", out.c_str());
|
||
printf("%s%s%s %s\n", col::green(), sym::check(), col::reset(), buf);
|
||
}
|
||
|
||
static int cmd_new(const Args& a) {
|
||
if (a.pos.empty()) { fprintf(stderr, "new: укажите путь модели\n"); return 1; }
|
||
const std::string out = a.pos[0];
|
||
const std::string corpus = a.get("corpus");
|
||
if (corpus.empty()) { fprintf(stderr, "new: нужен --corpus\n"); return 1; }
|
||
|
||
bool ok = false;
|
||
std::string text = read_all(corpus, ok);
|
||
if (!ok) { fprintf(stderr, "new: не читается %s\n", corpus.c_str()); return 1; }
|
||
|
||
// --from-json: словарь строится только по ТЕКСТАМ реплик, а не по всему JSON.
|
||
// Иначе ключи "role"/"content"/"messages" и фигурные скобки попадают в словарь
|
||
// как паразитные токены и съедают часть --vocab.
|
||
if (a.has("from-json")) {
|
||
std::string jerr;
|
||
std::string joined = extract_json_texts(text, jerr);
|
||
if (joined.empty()) {
|
||
fprintf(stderr, "new: --from-json не извлёк ни одной реплики: %s\n", jerr.c_str());
|
||
return 1;
|
||
}
|
||
printf("%s словарь строится по текстам реплик (%zu байт из %zu)\n",
|
||
sym::bullet(), joined.size(), text.size());
|
||
text = std::move(joined);
|
||
}
|
||
|
||
Checkpoint ck;
|
||
const DefaultsNew& dn = g_cfg.def_new;
|
||
ck.seed = (uint64_t)a.geti("seed", dn.seed);
|
||
ck.params.cfg.vocab_size = a.geti("vocab", dn.vocab);
|
||
ck.params.cfg.n_embd = a.geti("embd", dn.embd);
|
||
ck.params.cfg.n_layer = a.geti("layers", dn.layers);
|
||
ck.params.cfg.n_head = a.geti("heads", dn.heads);
|
||
ck.params.cfg.block_size = a.geti("ctx", dn.ctx);
|
||
ck.params.cfg.ffn_dim = a.geti("ffn", dn.ffn);
|
||
ck.params.cfg.rope_base = a.geti("rope", dn.rope);
|
||
// 0 = tied (выход делится с wte), -1 = untied (отдельная матрица lm_head).
|
||
// Раньше здесь стояло n_vocab_out = vocab_size, из-за чего tied() всё равно
|
||
// возвращал true и флаг --untied не делал ничего.
|
||
if (a.has("untied") || dn.untied) ck.params.cfg.n_vocab_out = -1;
|
||
|
||
std::string err;
|
||
// Проверяем конфигурацию ДО построения словаря: раньше на большом корпусе
|
||
// сначала выполнялась вся работа, и только потом сообщалось, что
|
||
// n_embd не делится на n_head.
|
||
if (!ck.params.cfg.valid(err)) { fprintf(stderr, "new: плохая конфигурация: %s\n", err.c_str()); return 1; }
|
||
|
||
Spinner sp("строю словарь по корпусу");
|
||
sp.start();
|
||
ck.tok.build_from_text(text, ck.params.cfg.vocab_size, a.has("view-vocab"));
|
||
sp.stop("словарь: " + std::to_string(ck.tok.size()) + " токенов");
|
||
ck.params.cfg.vocab_size = ck.tok.size();
|
||
|
||
if (ck.tok.size() < g_cfg.tokenizer.min_vocab) {
|
||
fprintf(stderr, "new: корпус дал всего %d токенов, нужно минимум %d\n",
|
||
ck.tok.size(), g_cfg.tokenizer.min_vocab);
|
||
return 1;
|
||
}
|
||
|
||
ck.params.init(ck.seed);
|
||
|
||
printf("создаю модель: %s\n", out.c_str());
|
||
print_model_info(ck);
|
||
size_t slash = out.find_last_of("/\\"); // оба разделителя: Windows допускает и '/' и '\'
|
||
if (slash != std::string::npos) mkdirs(out.substr(0, slash));
|
||
|
||
if (!save_checkpoint(out, ck, err)) { fprintf(stderr, "new: %s\n", err.c_str()); return 1; }
|
||
printf("готово. обучать: xenith train %s --corpus %s --out trained.xnh\n",
|
||
out.c_str(), corpus.c_str());
|
||
return 0;
|
||
}
|
||
|
||
static int cmd_train(const Args& a) {
|
||
if (a.pos.empty()) { fprintf(stderr, "train: укажите файл модели\n"); return 1; }
|
||
const std::string path = a.pos[0];
|
||
const std::string corpus = a.get("corpus");
|
||
if (corpus.empty()) { fprintf(stderr, "train: нужен --corpus\n"); return 1; }
|
||
|
||
Checkpoint ck;
|
||
std::string err;
|
||
if (!load_checkpoint(path, ck, err, load_opts(a, /*gen_only=*/false))) { fprintf(stderr, "train: %s\n", err.c_str()); return 1; }
|
||
|
||
const DefaultsTrain& dt = g_cfg.def_train;
|
||
TrainConfig tc;
|
||
tc.steps = a.geti("steps", dt.steps);
|
||
tc.batch_size = a.geti("batch", dt.batch);
|
||
tc.block = a.geti("block", dt.block);
|
||
tc.lr = a.getf("lr", dt.lr);
|
||
tc.weight_decay = a.getf("wd", dt.wd);
|
||
tc.clip = a.getf("clip", dt.clip);
|
||
tc.beta1 = a.getf("beta1", dt.beta1);
|
||
tc.beta2 = a.getf("beta2", dt.beta2);
|
||
tc.eps = a.getf("eps", dt.eps);
|
||
tc.warmup = a.geti("warmup", dt.warmup);
|
||
tc.lr_min_frac = a.getf("lr-min-frac", dt.lr_min_frac);
|
||
tc.seed = (uint64_t)a.geti("seed", dt.seed);
|
||
tc.log_every = a.geti("log-every", dt.log_every);
|
||
tc.ckpt_every = a.geti("ckpt-every", dt.ckpt_every);
|
||
tc.val_every = a.geti("val-every", dt.val_every);
|
||
tc.val_tokens = a.geti("val-tokens", dt.val_tokens);
|
||
tc.val_windows = a.geti("val-windows", dt.val_windows);
|
||
tc.threads = a.geti("threads", dt.threads);
|
||
// --- тип обучения: оптимизатор / накопление / сглаживание меток ---
|
||
tc.accum = std::max(1, a.geti("accum", dt.accum));
|
||
tc.label_smoothing = a.getf("label-smoothing", dt.label_smoothing);
|
||
{
|
||
const std::string opt_name = a.get("optimizer", dt.optimizer);
|
||
if (!optimizer_from_string(opt_name, tc.optimizer)) {
|
||
fprintf(stderr, "train: неизвестный --optimizer '%s' (adam|adamw|sgd|lion)\n",
|
||
opt_name.c_str());
|
||
return 1;
|
||
}
|
||
if (tc.label_smoothing < 0.0f || tc.label_smoothing >= 0.5f) {
|
||
fprintf(stderr, "train: --label-smoothing должен быть в [0, 0.5)\n");
|
||
return 1;
|
||
}
|
||
}
|
||
|
||
if (tc.threads > 0) set_threads(tc.threads);
|
||
if (tc.block > ck.params.cfg.block_size) tc.block = ck.params.cfg.block_size;
|
||
|
||
printf("обучаю %s\n", path.c_str());
|
||
print_model_info(ck);
|
||
printf(" шагов %d, батч %d, окно %d, lr %g\n\n", tc.steps, tc.batch_size, tc.block, tc.lr);
|
||
|
||
int resume = a.has("resume") ? ck.step : 0;
|
||
if (resume > 0) {
|
||
fprintf(stderr, "продолжаю с шага %d\n", resume);
|
||
}
|
||
|
||
std::string out = a.get("out", path);
|
||
|
||
ProgressBar bar;
|
||
auto prog = make_progress(bar, tc.steps, tc.log_every);
|
||
TrainStats st = train_model(ck.params, ck.tok, corpus, tc, out, resume, prog.first, prog.second);
|
||
finish_progress(bar, st, out);
|
||
return (st.step > 0) ? 0 : 1;
|
||
}
|
||
|
||
static int cmd_gen(const Args& a) {
|
||
if (a.pos.empty()) { fprintf(stderr, "gen: укажите файл модели\n"); return 1; }
|
||
Checkpoint ck;
|
||
std::string err;
|
||
LoadOptions lo = load_opts(a, /*gen_only=*/true);
|
||
if (a.has("ctx")) lo.gguf_ctx_cap = a.geti("ctx", 2048); // потолок контекста/KV-кэша
|
||
if (!load_checkpoint(a.pos[0], ck, err, lo)) { fprintf(stderr, "gen: %s\n", err.c_str()); return 1; }
|
||
if (a.has("ctx") && a.geti("ctx", 0) > 0) ck.params.cfg.block_size = a.geti("ctx", ck.params.cfg.block_size);
|
||
|
||
const DefaultsGen& dg = g_cfg.def_gen;
|
||
GenConfig gc;
|
||
gc.max_new_tokens = a.geti("n", dg.n);
|
||
gc.temperature = a.getf("temp", dg.temperature);
|
||
gc.top_k = a.geti("top-k", dg.top_k);
|
||
gc.top_p = a.getf("top-p", dg.top_p);
|
||
gc.repeat_penalty = a.getf("repeat-penalty", dg.repeat_penalty);
|
||
gc.seed = a.geti("seed", dg.seed);
|
||
gc.stream = a.has("stream") ? true : (a.has("no-stream") ? false : dg.stream);
|
||
|
||
if (a.has("batch")) {
|
||
std::vector<std::string> prompts;
|
||
std::string s = a.get("batch");
|
||
size_t start = 0;
|
||
while (start <= s.size()) {
|
||
size_t p = s.find(';', start);
|
||
if (p == std::string::npos) { prompts.push_back(s.substr(start)); break; }
|
||
prompts.push_back(s.substr(start, p - start));
|
||
start = p + 1;
|
||
}
|
||
gc.stream = false;
|
||
std::vector<std::string> outs = generate_batch(ck.params, ck.tok, prompts, gc);
|
||
for (size_t i = 0; i < outs.size(); ++i) {
|
||
printf("=== промпт %zu: %s\n%s\n\n", i + 1, prompts[i].c_str(), outs[i].c_str());
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
std::string prompt = a.get("prompt", "");
|
||
if (a.pos.size() > 1) prompt = a.pos[1];
|
||
|
||
std::vector<int> ids;
|
||
const std::string text = generate(ck.params, ck.tok, prompt, gc, &ids);
|
||
(void)text; // generate() возвращает текст ВМЕСТЕ с промптом — ниже режем по токенам
|
||
|
||
// Отделяем сгенерированный хвост от промпта: в ids лежат
|
||
// [токены промпта][сгенерированные токены].
|
||
const size_t plen = std::min(ck.tok.encode(prompt, true).size(), ids.size());
|
||
const std::vector<int> tail(ids.begin() + (long)plen, ids.end());
|
||
const std::string gen_text = ck.tok.decode(tail, /*skip_bos=*/true);
|
||
|
||
// --no-stream раньше не печатал ВООБЩЕ ничего: текст выводился только
|
||
// колбэком стриминга внутри generate().
|
||
if (!gc.stream) {
|
||
std::fputs(gen_text.c_str(), stdout);
|
||
std::fputc('\n', stdout);
|
||
}
|
||
|
||
// Модель немедленно выдала <eos> — без подсказки команда молча печатала
|
||
// пустую строку, и было непонятно, то ли она сломалась, то ли так и надо.
|
||
{
|
||
bool nothing = true; // пустой хвост — тоже «ничего не сгенерировано»
|
||
for (int id : tail)
|
||
if (id != ck.tok.bos && id != ck.tok.eos && id != ck.tok.user && id != ck.tok.asst)
|
||
{ nothing = false; break; }
|
||
if (nothing && gen_text.find_first_not_of(" \n\t\r") == std::string::npos)
|
||
fprintf(stderr, "%s модель не сгенерировала ни одного токена (сразу <eos>).\n"
|
||
" Обычно это значит, что модель недообучена или --temp слишком низкая;\n"
|
||
" попробуй --temp 0.8 --top-k 40 --n 100 или дообучи её (fine-tune).\n",
|
||
sym::warn());
|
||
}
|
||
|
||
if (a.has("show-tokens")) {
|
||
printf("\n--- токены (%zu) ---\n", ids.size());
|
||
for (size_t i = 0; i < ids.size(); ++i)
|
||
printf("%d ", ids[i]);
|
||
printf("\n");
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
static int cmd_info(const Args& a) {
|
||
if (a.pos.empty()) { fprintf(stderr, "info: укажите файл модели\n"); return 1; }
|
||
const std::string path = a.pos[0];
|
||
printf("файл: %s\n", path.c_str());
|
||
|
||
// safetensors: дамп контейнера (без чтения весов)
|
||
if (path_from_utf8(path).extension().string() == ".safetensors" ||
|
||
SafetensorsFile::is_safetensors_path(path)) {
|
||
std::string err;
|
||
const std::string dump = st_dump(path, err);
|
||
if (dump.empty()) { fprintf(stderr, "info: %s\n", err.c_str()); return 1; }
|
||
fputs(dump.c_str(), stdout);
|
||
ModelFileInfo mi = probe_checkpoint(path);
|
||
if (mi.ok)
|
||
printf("маппинг : %s поддерживается — модель можно загрузить\n", mi.arch.c_str());
|
||
else if (!mi.error.empty())
|
||
printf("маппинг : НЕ поддерживается — %s\n", mi.error.c_str());
|
||
return 0;
|
||
}
|
||
|
||
// GGUF: сначала контейнерный дамп (метаданные + тензоры без чтения весов),
|
||
// затем — если архитектура маппится — конфиг в терминах Xenith.
|
||
if (GgufFile::is_gguf_path(path)) {
|
||
std::string err;
|
||
const std::string dump = gguf_dump(path, err);
|
||
if (dump.empty()) { fprintf(stderr, "info: %s\n", err.c_str()); return 1; }
|
||
fputs(dump.c_str(), stdout);
|
||
ModelFileInfo mi = probe_checkpoint(path);
|
||
if (mi.ok) {
|
||
printf(" конфигурация Xenith (после импорта):\n");
|
||
printf(" слоёв : %d\n", mi.cfg.n_layer);
|
||
printf(" голов : %d (head_dim=%d)\n", mi.cfg.n_head, mi.cfg.head_dim());
|
||
printf(" размер эмбеддинга: %d\n", mi.cfg.n_embd);
|
||
printf(" FFN : %d (SwiGLU)\n", mi.cfg.ffn());
|
||
printf(" словарь : %d\n", mi.cfg.vocab_size);
|
||
printf(" контекст : %d\n", mi.cfg.block_size);
|
||
printf(" RoPE base : %d\n", mi.cfg.rope_base);
|
||
printf(" квантования : %s\n", mi.quant_summary.c_str());
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
Checkpoint ck;
|
||
std::string err;
|
||
if (!load_checkpoint(path, ck, err, load_opts(a, /*gen_only=*/true))) { fprintf(stderr, "info: %s\n", err.c_str()); return 1; }
|
||
print_model_info(ck);
|
||
if (ck.tok.bpe != BpeKind::None)
|
||
printf(" токенайзер : BPE (%s), слияний %zu\n",
|
||
bpe_kind_name(ck.tok.bpe), ck.tok.merges.size());
|
||
printf(" словарь (первые 40): ");
|
||
for (int i = 0; i < 40 && i < ck.tok.size(); ++i)
|
||
printf("%d=%s ", i, ck.tok.id2tok[i].c_str());
|
||
printf("%s\n", ck.tok.size() > 40 ? " ..." : "");
|
||
return 0;
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// convert / quantize / dequantize — мосты между .xnh и GGUF
|
||
// ---------------------------------------------------------------------------
|
||
static int cmd_convert(const Args& a, bool type_required) {
|
||
if (a.pos.size() < 2) {
|
||
fprintf(stderr,
|
||
"convert: использование — Xenith convert <in.xnh|in.gguf> <out.gguf|out.xnh> [--type q4_0]\n"
|
||
" (quantize: то же, но --type обязателен; dequantize: out обязан быть .xnh)\n");
|
||
return 1;
|
||
}
|
||
const std::string in = a.pos[0];
|
||
const std::string out = a.pos[1];
|
||
|
||
ConvertOptions co;
|
||
std::string err;
|
||
|
||
const bool has_type = a.has("type") || a.has("quant") || a.has("t");
|
||
const std::string tname = a.has("type") ? a.get("type")
|
||
: a.has("quant") ? a.get("quant")
|
||
: a.has("t") ? a.get("t") : "";
|
||
if (has_type) {
|
||
if (!qtype_from_name(tname, co.quant, err)) {
|
||
fprintf(stderr, "convert: %s\n", err.c_str());
|
||
return 1;
|
||
}
|
||
} else if (type_required) {
|
||
fprintf(stderr,
|
||
"quantize: укажите тип, например: Xenith quantize model.xnh model.q4_0.gguf --type q4_0\n"
|
||
" доступные типы: %s\n"
|
||
" псевдонимы: q6_0 = q6_K, fp16 = f16, fp32 = f32\n",
|
||
qtype_list_string().c_str());
|
||
return 1;
|
||
}
|
||
if (a.has("emb-type") && !qtype_from_name(a.get("emb-type"), co.emb_type, err)) {
|
||
fprintf(stderr, "convert: --emb-type: %s\n", err.c_str()); return 1;
|
||
}
|
||
co.emb_set = a.has("emb-type");
|
||
if (a.has("output-type") && !qtype_from_name(a.get("output-type"), co.output_type, err)) {
|
||
fprintf(stderr, "convert: --output-type: %s\n", err.c_str()); return 1;
|
||
}
|
||
co.output_set = a.has("output-type");
|
||
if (a.has("norms-quant")) co.norms_f32 = false;
|
||
if (a.has("keep-norms")) co.norms_f32 = true;
|
||
co.ctx_override = a.geti("ctx", 0);
|
||
co.alignment = (uint32_t)std::max(1, a.geti("alignment", 32));
|
||
co.name = a.get("name", "");
|
||
if (a.has("st-dtype")) {
|
||
std::string d = a.get("st-dtype");
|
||
for (char& ch : d) ch = (char)std::toupper((unsigned char)ch);
|
||
if (d != "F32" && d != "F16" && d != "BF16") {
|
||
fprintf(stderr, "convert: --st-dtype должен быть F32, F16 или BF16\n");
|
||
return 1;
|
||
}
|
||
co.st_dtype = d;
|
||
}
|
||
|
||
if (!fs::exists(path_from_utf8(in))) { fprintf(stderr, "convert: файл не найден: %s\n", in.c_str()); return 1; }
|
||
|
||
std::error_code ec;
|
||
const uint64_t in_bytes = (uint64_t)fs::file_size(path_from_utf8(in), ec);
|
||
|
||
if (!model_convert(in, out, co, err)) {
|
||
fprintf(stderr, "convert: %s\n", err.c_str());
|
||
return 1;
|
||
}
|
||
const uint64_t out_bytes = (uint64_t)fs::file_size(path_from_utf8(out), ec);
|
||
printf("%s%s%s %s -> %s\n", col::green(), sym::check(), col::reset(),
|
||
in.c_str(), out.c_str());
|
||
printf(" размер: %.2f МБ -> %.2f МБ%s\n",
|
||
in_bytes / 1048576.0, out_bytes / 1048576.0,
|
||
in_bytes ? "" : "");
|
||
const std::string out_ext = path_from_utf8(out).extension().string();
|
||
if (out_ext == ".gguf") {
|
||
printf(" тип весов: %s (%.3f bpw)%s\n",
|
||
qtype_name(co.quant), qtype_info(co.quant)->bpw(),
|
||
co.norms_f32 ? ", нормы f32" : "");
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
static int cmd_dequantize(const Args& a) {
|
||
if (a.pos.size() < 2) {
|
||
fprintf(stderr, "dequantize: использование — Xenith dequantize <model.gguf> <model.xnh> [--ctx N]\n");
|
||
return 1;
|
||
}
|
||
const std::string out_ext = path_from_utf8(a.pos[1]).extension().string();
|
||
if (out_ext != ".xnh") {
|
||
fprintf(stderr, "dequantize: выход должен быть .xnh (для gguf->gguf используйте quantize)\n");
|
||
return 1;
|
||
}
|
||
return cmd_convert(a, false);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// agent-demo — живая демонстрация агентного движка (IAgent/AgentContext/
|
||
// Router/NeuralAgent/MoE/multimodal/engine tick)
|
||
// ---------------------------------------------------------------------------
|
||
static int cmd_agent_demo(const Args& a) {
|
||
if (a.pos.empty()) {
|
||
fprintf(stderr, "agent-demo: укажите модель (.xnh/.gguf/.safetensors)\n");
|
||
return 1;
|
||
}
|
||
auto ck = std::make_shared<Checkpoint>();
|
||
std::string err;
|
||
LoadOptions lo;
|
||
lo.alloc_grads = false;
|
||
lo.want_optimizer = false;
|
||
if (a.has("ctx")) lo.gguf_ctx_cap = a.geti("ctx", 2048);
|
||
if (!load_checkpoint(a.pos[0], *ck, err, lo)) {
|
||
fprintf(stderr, "agent-demo: %s\n", err.c_str());
|
||
return 1;
|
||
}
|
||
const std::string prompt = a.has("prompt") ? a.get("prompt")
|
||
: (a.pos.size() > 1 ? a.pos[1] : std::string("привет"));
|
||
const int n_gen = a.geti("n", 12);
|
||
const int n_experts = std::max(1, a.geti("experts", 4));
|
||
const int top_k = std::max(1, a.geti("top-k", 2));
|
||
const std::string img = a.get("img", "");
|
||
const std::string wav = a.get("wav", "");
|
||
|
||
AgentEngine engine;
|
||
|
||
// (1)(7) сенсор: текст → токены; изображение/аудио → тензоры-эмбеддинги
|
||
const int d = ck->params.cfg.n_embd;
|
||
auto sensor = std::make_shared<LambdaAgent>("sensor", [&](AgentContext& c) {
|
||
if (c.tick == 0) {
|
||
c.tokens = ck->tok.encode(prompt, /*add_bos=*/true);
|
||
c.text["prompt"] = prompt;
|
||
c.state["prompt.tokens"] = (double)c.tokens.size();
|
||
// мультимодальность: патчи изображения и/или log-mel аудио
|
||
Tensor mm;
|
||
if (!img.empty()) {
|
||
mm::Image im;
|
||
std::string e;
|
||
if (!mm::load_ppm(img, im, e)) { fprintf(stderr, "img: %s\n", e.c_str()); return false; }
|
||
Tensor p = mm::image_to_patches(im, 4);
|
||
mm::Projector pr; pr.init(p.C(), d, 101);
|
||
Tensor pe; pr.apply(p, pe);
|
||
mm = mm::concat_rows(mm, pe);
|
||
c.state["img.patches"] = (double)p.R();
|
||
}
|
||
if (!wav.empty()) {
|
||
mm::Wav w;
|
||
std::string e;
|
||
if (!mm::load_wav(wav, w, e)) { fprintf(stderr, "wav: %s\n", e.c_str()); return false; }
|
||
Tensor mel = mm::wav_to_logmel(w, 256, 128, 24);
|
||
mm::Projector pr; pr.init(mel.C(), d, 202);
|
||
Tensor me; pr.apply(mel, me);
|
||
mm = mm::concat_rows(mm, me);
|
||
c.state["wav.frames"] = (double)mel.R();
|
||
}
|
||
if (mm.n() > 0) c.tensors["input.embedding"] = mm;
|
||
}
|
||
return true;
|
||
});
|
||
|
||
// MoE-эксперты поверх мультимодального входа (если он есть)
|
||
MoEParams mp;
|
||
mp.init(d, std::max(8, d), n_experts, std::min(top_k, n_experts), 31337);
|
||
auto moe = std::make_shared<MoEAgent>("moe", mp, "input.embedding", "moe.output");
|
||
|
||
// (5) «мозг»: NeuralAgent — токены ИЛИ эмбеддинги
|
||
auto brain = std::make_shared<NeuralAgent>("brain", ck);
|
||
brain->max_new_tokens = n_gen;
|
||
brain->gen.temperature = a.getf("temp", 0.8f);
|
||
brain->gen.top_k = a.geti("top-k-gen", 40);
|
||
brain->gen.seed = a.geti("seed", 7);
|
||
|
||
// контроллер-«критик»: пустой ответ → запросить повторный круг (rerun)
|
||
auto critic = std::make_shared<LambdaAgent>("critic", [&](AgentContext& c) {
|
||
const std::string& out = c.text.count("output.text") ? c.text["output.text"] : std::string();
|
||
bool empty = true;
|
||
for (char ch : out) if (!isspace((unsigned char)ch)) { empty = false; break; }
|
||
if (empty && c.num("critic.retries") < 1) {
|
||
c.state["critic.retries"] = c.num("critic.retries") + 1;
|
||
c.text["output.text"].clear();
|
||
c.rerun = true; // (2)(6) флаг повторного вычисления
|
||
}
|
||
return true;
|
||
});
|
||
|
||
engine.add_agent(sensor);
|
||
engine.add_agent(moe);
|
||
engine.add_agent(brain);
|
||
engine.add_agent(critic);
|
||
|
||
// (3) роутер: правила активируют разных агентов по состоянию контекста
|
||
auto router = std::make_shared<RouterScheduler>();
|
||
router->add_rule("init", [](const AgentContext& c) { return c.tick == 0; }, {"sensor"});
|
||
router->add_rule("multimodal", [](const AgentContext& c) { return c.has("input.embedding"); },
|
||
{"moe", "brain", "critic"});
|
||
router->add_rule("text", [](const AgentContext& c) { return !c.has("input.embedding"); },
|
||
{"brain", "critic"});
|
||
engine.set_scheduler(router);
|
||
engine.max_iterations = 3;
|
||
|
||
AgentContext ctx;
|
||
// Сенсор отрабатывает ДО первого плана роутера: планировщик видит контекст
|
||
// на старте такта, поэтому мультимодальные входы готовим заранее.
|
||
if (!sensor->process(ctx)) { fprintf(stderr, "agent-demo: сенсор\n"); return 1; }
|
||
if (!engine.run(ctx, err)) { fprintf(stderr, "agent-demo: %s\n", err.c_str()); return 1; }
|
||
|
||
printf("=== agent-demo ===\n");
|
||
printf(" модель : %s\n", a.pos[0].c_str());
|
||
printf(" промпт : %s (%d токенов)\n", prompt.c_str(), (int)ctx.num("prompt.tokens"));
|
||
if (ctx.num("img.patches") > 0) printf(" изображение : %s → %.0f патчей\n", img.c_str(), ctx.num("img.patches"));
|
||
if (ctx.num("wav.frames") > 0) printf(" аудио : %s → %.0f mel-кадров\n", wav.c_str(), ctx.num("wav.frames"));
|
||
printf(" итераций : %d (rerun=%s)\n", ctx.iterations, ctx.num("critic.retries") > 0 ? "был" : "нет");
|
||
if (ctx.has("moe.output")) {
|
||
const Tensor& m = ctx.tensors["moe.output"];
|
||
printf(" MoE : %d экспертов, top-%d → выход [%d x %d], |y|=%.3f\n",
|
||
n_experts, top_k, m.R(), m.C(), m.L2());
|
||
}
|
||
printf(" ответ мозга : %s\n", ctx.text.count("output.text") ? ctx.text["output.text"].c_str() : "");
|
||
printf(" токенов сгенерировано: %d\n", (int)ctx.num("output.tokens"));
|
||
return 0;
|
||
}
|
||
|
||
static int cmd_gradcheck(const Args& a) {
|
||
return run_gradcheck(a.has("verbose"));
|
||
}
|
||
|
||
static int cmd_bench(const Args& a) {
|
||
if (a.pos.empty()) { fprintf(stderr, "bench: укажите файл модели\n"); return 1; }
|
||
Checkpoint ck;
|
||
std::string err;
|
||
if (!load_checkpoint(a.pos[0], ck, err, load_opts(a, /*gen_only=*/true))) { fprintf(stderr, "bench: %s\n", err.c_str()); return 1; }
|
||
return run_bench(ck, a.geti("iters", 20), a.geti("block", 64));
|
||
}
|
||
|
||
// ===========================================================================
|
||
// fine-tune — дообучение на JSON-датасете диалогов
|
||
// ===========================================================================
|
||
static int cmd_fine_tune(const Args& a) {
|
||
if (a.pos.empty()) { fprintf(stderr, "fine-tune: укажите файл модели\n"); return 1; }
|
||
const std::string path = a.pos[0];
|
||
|
||
const std::string data = a.get("data", a.get("corpus"));
|
||
if (data.empty()) { fprintf(stderr, "fine-tune: нужен --data <датасет.json>\n"); return 1; }
|
||
|
||
// --- модель ---
|
||
Checkpoint ck;
|
||
std::string err;
|
||
if (!load_checkpoint(path, ck, err, load_opts(a, /*gen_only=*/false))) { fprintf(stderr, "fine-tune: %s\n", err.c_str()); return 1; }
|
||
|
||
std::string tok_err;
|
||
if (!validate_chat_tokenizer(ck.tok, tok_err)) {
|
||
fprintf(stderr, "fine-tune: %s\n", tok_err.c_str());
|
||
fprintf(stderr, " подсказка: пересоздай модель — xenith new models/chat.xnh --corpus corpus.txt ...\n");
|
||
return 1;
|
||
}
|
||
|
||
// --- дефолты fine-tune из config.yaml (нужны и для датасета, и для обучения) ---
|
||
const DefaultsFinetune& df = g_cfg.def_ft;
|
||
|
||
// --- настройки датасета: --ds-conf > defaults.fine_tune.dataset_conf ---
|
||
const std::string dsconf = a.get("ds-conf", df.dataset_conf);
|
||
DatasetConfig dc;
|
||
if (!dsconf.empty()) {
|
||
std::ifstream probe(path_from_utf8(dsconf));
|
||
if (!probe) {
|
||
fprintf(stderr, "fine-tune: файл настроек датасета не найден: %s\n", dsconf.c_str());
|
||
fprintf(stderr, " использую встроенные значения (или создай файл: xenith config --init-dataset)\n");
|
||
} else {
|
||
probe.close();
|
||
if (!load_dataset_config(dsconf, dc, err)) {
|
||
fprintf(stderr, "fine-tune: %s\n", err.c_str()); return 1;
|
||
}
|
||
}
|
||
}
|
||
// конфиг датасета тоже перекрывается флагами CLI
|
||
dc.loss_mask = a.has("no-mask") ? false : (a.has("mask") ? true : df.mask);
|
||
dc.user_loss = a.has("user-loss") ? true : df.user_loss;
|
||
dc.verbose = true;
|
||
|
||
// --- настройки обучения ---
|
||
TrainConfig tc;
|
||
tc.steps = a.geti("steps", df.steps);
|
||
tc.batch_size = a.geti("batch", df.batch);
|
||
tc.block = a.geti("block", df.block);
|
||
tc.lr = a.getf("lr", df.lr);
|
||
tc.weight_decay = a.getf("wd", df.wd);
|
||
tc.clip = a.getf("clip", df.clip);
|
||
tc.warmup = a.geti("warmup", df.warmup);
|
||
tc.lr_min_frac = a.getf("lr-min-frac", g_cfg.def_train.lr_min_frac);
|
||
tc.seed = (uint64_t)a.geti("seed", df.seed);
|
||
tc.log_every = a.geti("log-every", df.log_every);
|
||
tc.ckpt_every = a.geti("ckpt-every", df.ckpt_every);
|
||
tc.val_every = a.geti("val-every", df.val_every);
|
||
tc.val_tokens = a.geti("val-tokens", df.val_tokens);
|
||
tc.threads = a.geti("threads", df.threads);
|
||
// --- тип обучения: оптимизатор / накопление / сглаживание меток ---
|
||
tc.accum = std::max(1, a.geti("accum", df.accum));
|
||
tc.label_smoothing = a.getf("label-smoothing", df.label_smoothing);
|
||
{
|
||
const std::string opt_name = a.get("optimizer", df.optimizer);
|
||
if (!optimizer_from_string(opt_name, tc.optimizer)) {
|
||
fprintf(stderr, "fine-tune: неизвестный --optimizer '%s' (adam|adamw|sgd|lion)\n",
|
||
opt_name.c_str());
|
||
return 1;
|
||
}
|
||
if (tc.label_smoothing < 0.0f || tc.label_smoothing >= 0.5f) {
|
||
fprintf(stderr, "fine-tune: --label-smoothing должен быть в [0, 0.5)\n");
|
||
return 1;
|
||
}
|
||
}
|
||
if (tc.threads > 0) set_threads(tc.threads);
|
||
|
||
// блок не может превышать контекст модели
|
||
dc.block = std::min(tc.block, ck.params.cfg.block_size);
|
||
tc.block = dc.block;
|
||
|
||
// --- датасет ---
|
||
ParsedDataset ds = parse_chat_json_file(data, ck.tok, ck.params.cfg, dc);
|
||
if (!ds.ok()) { fprintf(stderr, "fine-tune: %s\n", ds.error.c_str()); return 1; }
|
||
ds.report();
|
||
|
||
tc.loss_mask = ds.cfg.loss_mask;
|
||
|
||
// флаг --resume: продолжить с сохранённого шага (Adam-state берётся из файла)
|
||
int resume = (a.has("resume") || (df.resume && !a.has("no-resume"))) ? ck.step : 0;
|
||
if (resume > 0) {
|
||
fprintf(stderr, "продолжаю с шага %d\n", resume);
|
||
if (resume >= tc.steps) {
|
||
fprintf(stderr, "fine-tune: шаг %d уже >= --steps %d. Передай --steps больше.\n",
|
||
resume, tc.steps);
|
||
return 1;
|
||
}
|
||
}
|
||
|
||
const std::string out = a.get("out", path);
|
||
printf("дообучаю %s на %s\n", path.c_str(), data.c_str());
|
||
print_model_info(ck);
|
||
printf(" шагов %d, батч %d, окно %d, lr %g, маска loss %s\n\n",
|
||
tc.steps, tc.batch_size, tc.block, tc.lr, tc.loss_mask ? "да" : "нет");
|
||
|
||
ProgressBar bar;
|
||
auto prog = make_progress(bar, tc.steps, tc.log_every);
|
||
TrainStats st = train_on_chat(ck.params, ck.tok, ds, tc, out, resume, prog.first, prog.second);
|
||
finish_progress(bar, st, out);
|
||
if (st.step == 0) { fprintf(stderr, "fine-tune: обучение не выполнилось\n"); return 1; }
|
||
|
||
printf("проверить: %schat %s%s\n", col::cyan(), out.c_str(), col::reset());
|
||
return 0;
|
||
}
|
||
|
||
// ===========================================================================
|
||
// chat — бесконечный цикл «запрос → ответ»
|
||
// ===========================================================================
|
||
static int cmd_chat(const Args& a) {
|
||
if (a.pos.empty()) { fprintf(stderr, "chat: укажите файл модели\n"); return 1; }
|
||
|
||
Checkpoint ck;
|
||
std::string err;
|
||
LoadOptions lo_chat = load_opts(a, /*gen_only=*/true);
|
||
if (a.has("ctx")) lo_chat.gguf_ctx_cap = a.geti("ctx", 2048); // потолок KV-кэша
|
||
if (!load_checkpoint(a.pos[0], ck, err, lo_chat)) { fprintf(stderr, "chat: %s\n", err.c_str()); return 1; }
|
||
if (a.has("ctx") && a.geti("ctx", 0) > 0) ck.params.cfg.block_size = a.geti("ctx", ck.params.cfg.block_size);
|
||
|
||
std::string tok_err;
|
||
if (!validate_chat_tokenizer(ck.tok, tok_err)) {
|
||
fprintf(stderr, "chat: %s\n", tok_err.c_str());
|
||
fprintf(stderr, " эта модель обучена как продолжатель текста — для чата нужен fine-tune\n");
|
||
return 1;
|
||
}
|
||
|
||
const DefaultsChat& dch = g_cfg.def_chat;
|
||
GenConfig gc;
|
||
gc.max_new_tokens = a.geti("n", dch.n);
|
||
gc.temperature = a.getf("temp", dch.temperature);
|
||
gc.top_k = a.geti("top-k", dch.top_k);
|
||
gc.top_p = a.getf("top-p", dch.top_p);
|
||
gc.repeat_penalty = a.getf("repeat-penalty", dch.repeat_penalty);
|
||
gc.seed = a.geti("seed", dch.seed);
|
||
gc.stream = a.has("stream") ? true : (a.has("no-stream") ? false : dch.stream);
|
||
const bool show_tokens = a.has("show-tokens");
|
||
const int threads = a.geti("threads", g_cfg.runtime.threads);
|
||
if (threads > 0) set_threads(threads);
|
||
// процент заполнения контекста, при котором предупреждаем о скорой обрезке
|
||
const int trim_pct = std::max(10, std::min(99, dch.context_trim_pct));
|
||
|
||
std::string sys = a.get("system", dch.system_prompt);
|
||
|
||
auto new_history = [&]() {
|
||
std::vector<int> h;
|
||
h.push_back(ck.tok.bos);
|
||
return h;
|
||
};
|
||
std::vector<int> history = new_history();
|
||
|
||
// системный промпт: отдельного токена <system> в словаре нет, поэтому
|
||
// приклеиваем его к первой реплике пользователя
|
||
std::string pending_system = a.has("no-system") ? std::string() : sys;
|
||
|
||
printf("Xenith chat — %s\n", a.pos[0].c_str());
|
||
print_model_info(ck);
|
||
printf(" контекст %d токенов, temp %.2f, top_k %d, top_p %.2f, n %d\n",
|
||
ck.params.cfg.block_size, gc.temperature, gc.top_k, gc.top_p, gc.max_new_tokens);
|
||
printf(" команды: /exit /reset /history /save <путь> /model /help\n\n");
|
||
|
||
std::string line;
|
||
int turn = 0;
|
||
while (true) {
|
||
printf("ты> ");
|
||
std::fflush(stdout);
|
||
if (!std::getline(std::cin, line)) { printf("\n"); break; }
|
||
|
||
// --- служебные команды ---
|
||
if (!line.empty() && line[0] == '/') {
|
||
std::istringstream cs(line);
|
||
std::string cmd, arg;
|
||
cs >> cmd >> arg;
|
||
if (cmd == "/exit" || cmd == "/quit" || cmd == "/q") break;
|
||
if (cmd == "/help") {
|
||
printf(" /exit выйти\n"
|
||
" /reset очистить историю диалога\n"
|
||
" /history показать историю в токенах\n"
|
||
" /save <путь> сохранить модель с текущими весами\n"
|
||
" /model конфигурация модели\n"
|
||
" /temp <f> температура\n"
|
||
" /n <int> максимум токенов в ответе\n");
|
||
continue;
|
||
}
|
||
if (cmd == "/reset") {
|
||
history = new_history();
|
||
pending_system = a.has("no-system") ? std::string() : sys;
|
||
turn = 0;
|
||
printf(" история очищена\n");
|
||
continue;
|
||
}
|
||
if (cmd == "/history") {
|
||
printf(" %zu токенов из %d:\n ", history.size(), ck.params.cfg.block_size);
|
||
for (size_t i = 0; i < history.size(); ++i) {
|
||
printf("%d", history[i]);
|
||
if (i + 1 < history.size()) printf(" ");
|
||
}
|
||
printf("\n текст: %s\n", ck.tok.decode(history, true).c_str());
|
||
continue;
|
||
}
|
||
if (cmd == "/save") {
|
||
if (arg.empty()) { printf(" /save <путь.xnh>\n"); continue; }
|
||
// БЕЗ копии Checkpoint: раньше здесь создавался второй
|
||
// экземпляр всех весов (`Checkpoint out_ck{ck.params, ...}`).
|
||
std::string serr;
|
||
if (save_checkpoint(arg, ck.params, ck.tok, turn, 0.0f, ck.seed, serr))
|
||
printf(" сохранено: %s\n", arg.c_str());
|
||
else printf(" ошибка: %s\n", serr.c_str());
|
||
continue;
|
||
}
|
||
if (cmd == "/model") { print_model_info(ck); continue; }
|
||
if (cmd == "/temp") { if (!arg.empty()) { gc.temperature = (float)std::atof(arg.c_str()); printf(" temp = %.2f\n", gc.temperature); } continue; }
|
||
if (cmd == "/n") { if (!arg.empty()) { gc.max_new_tokens = std::atoi(arg.c_str()); printf(" n = %d\n", gc.max_new_tokens); } continue; }
|
||
if (cmd == "/backend") {
|
||
printf(" вычислительный бэкенд: %s%s%s\n", col::cyan(), backend()->name(), col::reset());
|
||
printf(" устройство : %s\n", backend()->describe().c_str());
|
||
if (vulkan_available()) {
|
||
auto devs = vulkan_list_devices();
|
||
if (devs.empty()) printf(" Vulkan-устройств не найдено\n");
|
||
else for (auto& d : devs) printf(" %s\n", d.c_str());
|
||
} else printf(" Vulkan: сборка без -DXENITH_VULKAN=ON\n");
|
||
continue;
|
||
}
|
||
if (cmd == "/config") { config_dump(g_cfg, /*all=*/true); continue; }
|
||
printf(" неизвестная команда: %s (есть /help)\n", cmd.c_str());
|
||
continue;
|
||
}
|
||
|
||
// пустая строка — не ход
|
||
bool only_space = true;
|
||
for (char ch : line) if (!std::isspace((unsigned char)ch)) { only_space = false; break; }
|
||
if (only_space) continue;
|
||
|
||
std::string turn_text = line;
|
||
if (!pending_system.empty()) {
|
||
turn_text = pending_system + "\n" + line;
|
||
pending_system.clear();
|
||
}
|
||
|
||
printf("бот> ");
|
||
std::fflush(stdout);
|
||
|
||
GenOutStats st;
|
||
TokenCallback cb;
|
||
if (gc.stream) {
|
||
cb = [&ck](int id, const std::string& piece) {
|
||
std::fputs(piece.c_str(), stdout);
|
||
if (id >= Tokenizer::n_special && id < ck.tok.size() && ck.tok.id2tok[id].size() > 1)
|
||
std::fputc(' ', stdout);
|
||
std::fflush(stdout);
|
||
};
|
||
}
|
||
|
||
const size_t hist_before = history.size();
|
||
const std::string answer = chat_turn(ck.params, ck.tok, history, turn_text, gc, &st, cb);
|
||
++turn;
|
||
|
||
if (!gc.stream) printf("%s", answer.c_str());
|
||
printf("\n");
|
||
|
||
if (show_tokens) {
|
||
printf(" --- сгенерировано %d токенов, стоп: %s ---\n ", st.n_tokens(), st.stop_reason.c_str());
|
||
for (int id : st.tokens) printf("%d ", id);
|
||
printf("\n");
|
||
}
|
||
if (st.stop_reason == "role")
|
||
printf(" [!] модель выдала <user> — она пытается отвечать за обе роли. "
|
||
"Нужна маска loss (--mask) или больше данных.\n");
|
||
if (st.stop_reason == "length")
|
||
printf(" [!] упёрлись в --n %d, ответ обрезан\n", gc.max_new_tokens);
|
||
|
||
// предупреждение о переполнении контекста (порог — из config.yaml)
|
||
if ((int)history.size() * 100 > ck.params.cfg.block_size * trim_pct)
|
||
printf(" %s[i]%s история %zu/%d токенов — скоро начнёт обрезаться начало "
|
||
"(потеряется системный промпт). /reset — начать заново.\n",
|
||
col::yellow(), col::reset(), history.size(), ck.params.cfg.block_size);
|
||
(void)hist_before;
|
||
}
|
||
|
||
printf("всего ходов: %d\n", turn);
|
||
return 0;
|
||
}
|
||
|
||
// ===========================================================================
|
||
// ollama — HTTP-сервер, совместимый с Ollama API
|
||
// ===========================================================================
|
||
static int cmd_ollama(const Args& a) {
|
||
OllamaOptions opt;
|
||
opt.cfg = g_cfg; // сервер берёт host/port/модели из config.yaml
|
||
// CLI перекрывает конфиг
|
||
opt.conf = a.get("conf", a.get("config"));
|
||
opt.port = a.has("port") ? a.geti("port", g_cfg.server.port) : g_cfg.server.port;
|
||
opt.host = a.has("host") ? a.get("host", g_cfg.server.host) : g_cfg.server.host;
|
||
opt.default_model = a.has("model") ? a.get("model", g_cfg.server.default_model)
|
||
: g_cfg.server.default_model;
|
||
opt.verbose = a.has("verbose") || a.has("v") || g_cfg.server.verbose;
|
||
if (a.has("no-scan")) opt.scan_models_dir = false;
|
||
else opt.scan_models_dir = g_cfg.server.scan_models;
|
||
// Помечаем, что задано именно в командной строке: --conf не должен это
|
||
// перекрывать (приоритет CLI > --conf > config.yaml).
|
||
opt.cli_port = a.has("port");
|
||
opt.cli_host = a.has("host");
|
||
opt.cli_model = a.has("model");
|
||
opt.cli_verbose = a.has("verbose") || a.has("v");
|
||
opt.cli_no_scan = a.has("no-scan");
|
||
return run_ollama_server(opt);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// config — показать/создать настройки проекта
|
||
// ---------------------------------------------------------------------------
|
||
static int cmd_config(const Args& a) {
|
||
if (a.has("init")) {
|
||
// --init [PATH]: путь может прийти значением флага (так его кладёт
|
||
// Args) или позиционным аргументом; "1" — маркер флага без значения.
|
||
std::string path = a.get("init");
|
||
if (path.empty() || path == "1")
|
||
path = a.pos.empty() ? "config.yaml" : a.pos[0];
|
||
std::error_code ec;
|
||
if (fs::exists(path_from_utf8(path), ec) && !a.has("force")) {
|
||
fprintf(stderr, "config: %s уже существует (перезаписать: --force)\n", path.c_str());
|
||
return 1;
|
||
}
|
||
std::string err;
|
||
if (!config_write_default(path, err)) { fprintf(stderr, "config: %s\n", err.c_str()); return 1; }
|
||
printf("%s%s%s записан %s\n", col::green(), sym::check(), col::reset(), path.c_str());
|
||
return 0;
|
||
}
|
||
if (a.has("path")) {
|
||
printf("%s\n", g_cfg.config_path.empty() ? "<не найден>" : g_cfg.config_path.c_str());
|
||
return 0;
|
||
}
|
||
if (a.has("get")) {
|
||
// Ключ может прийти значением флага (--get server.port / --get=server.port)
|
||
// либо отдельным позиционным аргументом. Раньше читался ТОЛЬКО a.pos[0],
|
||
// а парсер Args укладывал ключ в kv["get"], поэтому команда печатала
|
||
// весь дамп вместо значения.
|
||
std::string key = a.get("get");
|
||
if (key.empty() || key == "1") key = a.pos.empty() ? std::string() : a.pos[0];
|
||
if (key.empty()) {
|
||
fprintf(stderr, "config --get: нужен ключ, например: xenith config --get server.port\n");
|
||
return 1;
|
||
}
|
||
const YamlNode* n = g_cfg.raw.path(key);
|
||
if (!n) { fprintf(stderr, "нет такого ключа: %s\n", key.c_str()); return 1; }
|
||
if (n->is_scalar()) printf("%s\n", n->scalar.c_str());
|
||
else if (n->is_seq()) {
|
||
for (auto& e : n->seq) printf("%s\n", (e && e->is_scalar()) ? e->scalar.c_str() : "-");
|
||
} else if (n->is_map()) {
|
||
// раздел: печатаем дочерние ключи, чтобы было видно структуру
|
||
printf("<раздел, %zu ключ(ей)>\n", n->map.size());
|
||
for (auto& kv : n->map) {
|
||
if (kv.second && kv.second->is_scalar()) printf(" %s: %s\n", kv.first.c_str(), kv.second->scalar.c_str());
|
||
else printf(" %s: <%s>\n", kv.first.c_str(),
|
||
kv.second && kv.second->is_seq() ? "список" : "раздел");
|
||
}
|
||
} else {
|
||
printf("<пусто>\n"); // было разыменование nullptr, если ключ есть, а значения нет
|
||
}
|
||
return 0;
|
||
}
|
||
config_dump(g_cfg, a.has("all")); // --all добавляет vulkan/log/checkpoint/tokenizer
|
||
printf("\n файл настроек : %s\n", g_cfg.config_path.empty() ? "<используются встроенные дефолты>"
|
||
: g_cfg.config_path.c_str());
|
||
printf(" создать файл : %sxenith config --init%s\n", col::cyan(), col::reset());
|
||
return 0;
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// doctor — диагностика окружения
|
||
// ---------------------------------------------------------------------------
|
||
static int cmd_doctor(const Args&) {
|
||
printf("%s диагностика%s\n", col::bold(), col::reset());
|
||
printf(" версия : %s\n", g_cfg.version.c_str());
|
||
if (!g_cfg.commit.empty()) printf(" коммит : %s\n", g_cfg.commit.c_str());
|
||
if (!g_cfg.build_type.empty()) printf(" тип сборки : %s\n", g_cfg.build_type.c_str());
|
||
printf(" каталог bin : %s\n", executable_dir().c_str());
|
||
printf(" config.yaml : %s\n", g_cfg.config_path.empty() ? "НЕ НАЙДЕН (работаем на дефолтах)"
|
||
: g_cfg.config_path.c_str());
|
||
printf(" бэкенд : %s (%s)\n", backend()->name(), backend()->describe().c_str());
|
||
printf(" потоков : %d (cap %d)\n", hw_threads(), threads_cap());
|
||
|
||
printf("\n %sHTTP-инструменты%s\n", col::bold(), col::reset());
|
||
auto tools = http_available_tools();
|
||
if (tools.empty()) printf(" %sнет ни одного%s — команда update работать не будет\n",
|
||
col::red(), col::reset());
|
||
else { printf(" "); for (size_t i=0;i<tools.size();++i) printf("%s%s", i?", ":"", tools[i].c_str()); printf("\n"); }
|
||
|
||
printf("\n %sVulkan%s\n", col::bold(), col::reset());
|
||
if (!vulkan_available()) printf(" сборка без -DXENITH_VULKAN=ON\n");
|
||
else {
|
||
auto devs = vulkan_list_devices();
|
||
if (devs.empty()) printf(" устройств не найдено\n");
|
||
else for (auto& d : devs) printf(" %s\n", d.c_str());
|
||
}
|
||
|
||
printf("\n %sкаталоги%s\n", col::bold(), col::reset());
|
||
for (const std::string& d : {g_cfg.runtime.models_dir, g_cfg.runtime.tmp_dir}) {
|
||
std::error_code ec;
|
||
printf(" %-12s %s\n", d.c_str(), fs::is_directory(path_from_utf8(d), ec) ? "есть" : "отсутствует");
|
||
}
|
||
|
||
printf("\n %sсвязь с репозиторием%s\n", col::bold(), col::reset());
|
||
Spinner sp("проверяю " + g_cfg.update.repo);
|
||
sp.start();
|
||
UpdateStatus st = check_for_update(g_cfg.update, g_cfg.version, g_cfg.commit);
|
||
sp.stop(update_result_name(st.result));
|
||
printf(" локальная %s, в репозитории %s\n",
|
||
semver_str(st.local).c_str(), semver_str(st.remote).c_str());
|
||
if (!st.error.empty()) printf(" %s%s%s\n", col::red(), st.error.c_str(), col::reset());
|
||
return 0;
|
||
}
|
||
|
||
|
||
// Правильное сравнение версий
|
||
|
||
|
||
static int cmd_update(const Args& a) {
|
||
UpdateSettings us = g_cfg.update;
|
||
if (a.has("no-tls-check")) us.verify_tls = false;
|
||
if (a.has("prerelease")) us.allow_prerelease = true;
|
||
// --check : только узнать версию, план установки не печатаем
|
||
// --dry-run: узнать версию И показать, что именно будет сделано
|
||
const bool dry = a.has("dry-run");
|
||
const bool check_only = a.has("check") || dry;
|
||
|
||
if (!us.enabled && !a.has("force")) {
|
||
printf("обновление выключено в config.yaml (update.enabled: false). Обойти: --force\n");
|
||
return 1; // команда отказалась работать — это не успех
|
||
}
|
||
|
||
Spinner sp("спрашиваю репозиторий " + us.repo);
|
||
sp.start();
|
||
UpdateStatus st = check_for_update(us, g_cfg.version, g_cfg.commit);
|
||
switch (st.result) {
|
||
case UpdateResult::NewerAvailable: sp.stop("есть новая версия"); break;
|
||
case UpdateResult::UpToDate: sp.stop("версия актуальна"); break;
|
||
case UpdateResult::SameVersionNewCommits: sp.stop("версия та же, есть новые коммиты"); break;
|
||
case UpdateResult::LocalIsNewer: sp.stop("локальная версия новее"); break;
|
||
default: sp.fail("проверить не удалось"); break;
|
||
}
|
||
|
||
printf("\n");
|
||
printf(" %s%-18s%s %s%s%s\n", col::grey(), "локальная версия", col::reset(),
|
||
col::bold(), semver_str(st.local).c_str(), col::reset());
|
||
if (!g_cfg.commit.empty())
|
||
printf(" %s%-18s%s %s\n", col::grey(), "коммит сборки", col::reset(), g_cfg.commit.c_str());
|
||
printf(" %s%-18s%s %s\n", col::grey(), "в репозитории", col::reset(),
|
||
semver_str(st.remote).c_str());
|
||
if (!st.remote_tag.empty())
|
||
printf(" %s%-18s%s %s%s\n", col::grey(), "тег релиза", col::reset(), st.remote_tag.c_str(),
|
||
st.remote_prerelease ? " (prerelease)" : "");
|
||
if (!st.remote_commit.empty())
|
||
printf(" %s%-18s%s %s\n", col::grey(), "HEAD ветки", col::reset(), st.remote_commit.substr(0, 8).c_str());
|
||
if (st.commits_behind > 0)
|
||
printf(" %s%-18s%s на %d комм. дальше\n", col::grey(), "репозиторий", col::reset(), st.commits_behind);
|
||
else if (st.commits_behind < 0 && !st.remote_commit.empty())
|
||
printf(" %s%-18s%s не удалось сравнить коммиты\n", col::grey(), "", col::reset());
|
||
if (!st.via.empty())
|
||
printf(" %s%-18s%s %s\n", col::grey(), "запрос через", col::reset(), st.via.c_str());
|
||
|
||
if (!st.error.empty()) { printf("\n %s%s%s\n", col::red(), st.error.c_str(), col::reset()); }
|
||
|
||
switch (st.result) {
|
||
case UpdateResult::UpToDate:
|
||
printf("\n%s%s%s обновлять нечего\n", col::green(), sym::check(), col::reset());
|
||
return 0;
|
||
case UpdateResult::SameVersionNewCommits:
|
||
printf("\n%s%s%s версия не изменилась — НЕ обновляюсь.\n", col::yellow(), sym::warn(), col::reset());
|
||
printf(" В репозитории есть новые коммиты (%d), но это рабочая разработка,\n", st.commits_behind);
|
||
printf(" а не релиз. Обновление по коммитам намеренно отключено:\n");
|
||
printf(" натягивание нестабильного master на установленную версию ломает модели.\n");
|
||
printf(" Если очень нужно — собери из ветки вручную: git clone --branch %s %s\n",
|
||
us.branch.c_str(), us.repo.c_str());
|
||
return 0;
|
||
case UpdateResult::LocalIsNewer:
|
||
printf("\n%s%s%s локальная сборка новее репозитория — не обновляюсь\n",
|
||
col::yellow(), sym::warn(), col::reset());
|
||
return 0;
|
||
case UpdateResult::CheckFailed:
|
||
printf("\n%s%s%s проверка не удалась\n", col::red(), sym::cross(), col::reset());
|
||
return 1;
|
||
default: break;
|
||
}
|
||
|
||
printf("\n%s%s%s доступна версия %s%s%s\n", col::green(), sym::arrow(), col::reset(),
|
||
col::bold(), semver_str(st.remote).c_str(), col::reset());
|
||
|
||
const std::string dir = a.get("dir", us.install_dir.empty() ? executable_dir() : us.install_dir);
|
||
printf(" каталог установки: %s\n", dir.c_str());
|
||
printf(" сохраняем : ");
|
||
for (size_t i = 0; i < us.keep.size(); ++i) printf("%s%s", i ? ", " : "", us.keep[i].c_str());
|
||
printf("\n резервная копия : %s/<timestamp>\n", us.backup_dir.c_str());
|
||
|
||
if (check_only) {
|
||
std::string err;
|
||
if (dry) apply_update(us, st, dir, err, /*dry_run=*/true);
|
||
printf("\n%s%s: ничего не меняю%s\n", col::yellow(), dry ? "--dry-run" : "--check", col::reset());
|
||
return 0;
|
||
}
|
||
if (us.policy != UpdatePolicy::Auto && !a.has("yes")) {
|
||
printf("\nустановить? [y/N] ");
|
||
fflush(stdout);
|
||
std::string ans;
|
||
if (!std::getline(std::cin, ans)) return 1;
|
||
if (ans != "y" && ans != "Y" && ans != "yes" && ans != "д" && ans != "Д") {
|
||
printf("отменено\n");
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
std::string err;
|
||
Spinner inst("устанавливаю " + semver_str(st.remote));
|
||
inst.start();
|
||
const UpdateResult r = apply_update(us, st, dir, err, false);
|
||
if (r != UpdateResult::Installed) {
|
||
inst.fail("обновление не установлено");
|
||
fprintf(stderr, " %s\n", err.c_str());
|
||
return 1;
|
||
}
|
||
inst.stop("установлено");
|
||
printf("\n%s%s%s версия %s. Перезапусти xenith, чтобы подхватить новый бинарник.\n",
|
||
col::green(), sym::check(), col::reset(), semver_str(st.remote).c_str());
|
||
return 0;
|
||
}
|
||
|
||
static int cmd_shaders(const Args& a) {
|
||
const std::string dir = a.get("dir", "");
|
||
if (a.has("rebuild")) {
|
||
std::string err;
|
||
printf("перекомпилирую шейдеры%s...\n",
|
||
dir.empty() ? "" : (" в " + dir).c_str());
|
||
if (!vulkan_rebuild_shaders(err, dir)) {
|
||
fprintf(stderr, "shaders: %s\n", err.c_str());
|
||
return 1;
|
||
}
|
||
printf("%s шейдеры собраны\n", sym::check());
|
||
return 0;
|
||
}
|
||
const std::string d = dir.empty() ? vulkan_shader_dir() : dir;
|
||
if (d.empty()) {
|
||
fprintf(stderr, "shaders: каталог shaders/ не найден. Положи его рядом с "
|
||
"бинарником или задай --dir / XENITH_SHADER_DIR\n");
|
||
return 1;
|
||
}
|
||
printf("%s\n", d.c_str());
|
||
return 0;
|
||
}
|
||
|
||
static int cmd_manifest(const Args& a) {
|
||
const std::string dir = a.get("dir", executable_dir());
|
||
const std::string out = a.get("out", dir + "/updates/manifest.json");
|
||
const std::string ver = a.get("version", g_cfg.version);
|
||
const std::string tag = a.get("tag", "v" + ver);
|
||
const std::string base = a.get("base", "");
|
||
std::string err;
|
||
if (!write_update_manifest(dir, out, ver, tag, base, err)) {
|
||
fprintf(stderr, "manifest: %s\n", err.c_str());
|
||
return 1;
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
static int cmd_backends(const Args&) {
|
||
printf("%sCPU%s : доступен всегда (встроен в бинарник)\n",
|
||
col::green(), col::reset());
|
||
if (!vulkan_available()) {
|
||
printf("%sVulkan%s: не собран (XENITH_VULKAN=OFF) — только CPU\n",
|
||
col::yellow(), col::reset());
|
||
return 0;
|
||
}
|
||
printf("%sVulkan%s: собран в бинарник; загрузчик ищется в рантайме\n",
|
||
col::cyan(), col::reset());
|
||
auto devs = vulkan_list_devices();
|
||
const std::string le = vulkan_loader_error();
|
||
if (!le.empty())
|
||
printf(" загрузчик: %s\n", le.c_str());
|
||
else
|
||
printf(" загрузчик: OK\n");
|
||
if (devs.empty()) {
|
||
printf(" runtime : Vulkan-устройств нет — программа остаётся на CPU\n");
|
||
} else {
|
||
printf(" runtime : %zu устройство(й)\n", devs.size());
|
||
for (const auto& d : devs) printf(" %s\n", d.c_str());
|
||
}
|
||
const std::string sd = vulkan_shader_dir();
|
||
if (sd.empty()) {
|
||
printf(" shaders : каталог не найден; используется встроенный SPIR-V\n");
|
||
} else {
|
||
int nc = 0, ns = 0;
|
||
std::error_code ec;
|
||
for (auto& e : std::filesystem::directory_iterator(path_from_utf8(sd), ec)) {
|
||
if (!e.is_regular_file(ec)) continue;
|
||
const std::string ext = e.path().extension().string();
|
||
if (ext == ".comp") ++nc;
|
||
else if (ext == ".spv") ++ns;
|
||
}
|
||
printf(" shaders : %s (%d .comp, %d .spv)\n", sd.c_str(), nc, ns);
|
||
printf(" если .spv нет — .comp компилируется при первом использовании\n");
|
||
}
|
||
printf("\nпереключение: --cpu / --vulkan (перекомпиляция не нужна)\n");
|
||
return 0;
|
||
}
|
||
|
||
int main(int argc, char** argv) {
|
||
#ifdef _WIN32
|
||
// Консоль Windows по умолчанию в ACP — кириллица из UTF-8-вывода движка
|
||
// превращалась в мусор.
|
||
::SetConsoleOutputCP(CP_UTF8);
|
||
::SetConsoleCP(CP_UTF8);
|
||
|
||
// argv на Windows приходит в ANSI-кодировке. Берём UTF-16 командную
|
||
// строку и конвертируем в UTF-8 один раз здесь — пути и промпты с
|
||
// кириллицей перестают теряться.
|
||
int wargc = 0;
|
||
LPWSTR* wargv = ::CommandLineToArgvW(::GetCommandLineW(), &wargc);
|
||
std::vector<std::string> arg_store;
|
||
std::vector<char*> arg_ptrs;
|
||
if (wargv) {
|
||
arg_store.reserve((size_t)wargc);
|
||
for (int i = 0; i < wargc; ++i)
|
||
arg_store.push_back(path_to_utf8(fs::path(wargv[i])));
|
||
::LocalFree(wargv);
|
||
for (auto& s : arg_store) arg_ptrs.push_back(const_cast<char*>(s.c_str()));
|
||
argc = wargc;
|
||
argv = arg_ptrs.data();
|
||
}
|
||
#endif
|
||
// -----------------------------------------------------------------------
|
||
// 1. Аргументы разбираем ДО конфига: --config и --backend влияют на загрузку
|
||
// -----------------------------------------------------------------------
|
||
std::string cmd;
|
||
std::string cli_config;
|
||
std::vector<std::string> rest;
|
||
rest.reserve((size_t)argc);
|
||
for (int i = 1; i < argc; ++i) {
|
||
const std::string a = argv[i];
|
||
// --help/--version/-h/-v первым аргументом — это тоже команды: раньше они
|
||
// не попадали в cmd (условие a.rfind("--",0)!=0), справка печаталась, но
|
||
// код возврата был 1, а ветка cmd=="--version" оказывалась мёртвой.
|
||
if (cmd.empty() && (a == "--help" || a == "-h" || a == "--version" || a == "-v")) {
|
||
cmd = a; continue;
|
||
}
|
||
if (cmd.empty() && a.rfind("--", 0) != 0) { cmd = a; continue; }
|
||
if (a == "--config" || a == "-c") {
|
||
if (i + 1 < argc) cli_config = argv[++i];
|
||
continue;
|
||
}
|
||
if (a.rfind("--config=", 0) == 0) { cli_config = a.substr(9); continue; }
|
||
rest.push_back(a);
|
||
}
|
||
|
||
// -----------------------------------------------------------------------
|
||
// 2. Настройки проекта: config.yaml → XENITH_* → дефолты
|
||
// -----------------------------------------------------------------------
|
||
std::string cfg_err;
|
||
if (!config_load(g_cfg, cli_config, cfg_err)) {
|
||
fprintf(stderr, "%s %s%s\n", col::red(), cfg_err.c_str(), col::reset());
|
||
fprintf(stderr, " исправь файл или запусти: xenith config --init --force\n");
|
||
return 1;
|
||
}
|
||
|
||
// UI и логирование настраиваются до любого вывода
|
||
ui_configure(g_cfg.ui.color, g_cfg.ui.progress, g_cfg.ui.eta, g_cfg.ui.sparkline,
|
||
g_cfg.ui.spinner, g_cfg.ui.bar_width, g_cfg.ui.ascii_only);
|
||
log_init(g_cfg.log);
|
||
for (const auto& w : g_cfg.warnings) LOGW("%s", w.c_str());
|
||
|
||
set_threads_cap(g_cfg.runtime.threads_cap);
|
||
if (g_cfg.runtime.threads > 0) set_threads(g_cfg.runtime.threads);
|
||
|
||
if (cmd.empty() || cmd == "-h" || cmd == "--help" || cmd == "help") {
|
||
printf("%s", HELP_TEXT.c_str());
|
||
printf("\nВЕРСИЯ\n");
|
||
printf(" %s %s", g_cfg.name.c_str(), g_cfg.version.c_str());
|
||
if (!g_cfg.commit.empty()) printf(" (%s)", g_cfg.commit.c_str());
|
||
if (!g_cfg.build_type.empty()) printf(" [%s]", g_cfg.build_type.c_str());
|
||
printf("\n config.yaml: %s\n", g_cfg.config_path.empty() ? "<не найден — встроенные дефолты>"
|
||
: g_cfg.config_path.c_str());
|
||
printf(" подробности: %sxenith config%s, диагностика: %sxenith doctor%s\n",
|
||
col::cyan(), col::reset(), col::cyan(), col::reset());
|
||
return cmd.empty() ? 1 : 0;
|
||
}
|
||
|
||
std::vector<char*> fake_argv;
|
||
fake_argv.push_back(argv[0]);
|
||
for (auto& r : rest) fake_argv.push_back(const_cast<char*>(r.c_str()));
|
||
Args args((int)fake_argv.size(), fake_argv.data(), 1);
|
||
|
||
init_backend(args, cmd);
|
||
|
||
if (cmd != "update" && cmd != "doctor" && cmd != "config" && cmd != "help")
|
||
maybe_notify_update(g_cfg);
|
||
|
||
if (cmd == "version" || cmd == "-v" || cmd == "--version") {
|
||
printf("%s %s", g_cfg.name.c_str(), g_cfg.version.c_str());
|
||
if (!g_cfg.commit.empty()) printf(" (%s)", g_cfg.commit.c_str());
|
||
if (!g_cfg.build_type.empty()) printf(" [%s]", g_cfg.build_type.c_str());
|
||
printf("\nбэкенд: %s (%s)\n", backend()->name(), backend()->describe().c_str());
|
||
return 0;
|
||
}
|
||
if (cmd == "config") return cmd_config(args);
|
||
if (cmd == "doctor") return cmd_doctor(args);
|
||
if (cmd == "new") return cmd_new(args);
|
||
if (cmd == "train") return cmd_train(args);
|
||
if (cmd == "gen") return cmd_gen(args);
|
||
if (cmd == "info") return cmd_info(args);
|
||
if (cmd == "gradcheck") return cmd_gradcheck(args);
|
||
if (cmd == "bench") return cmd_bench(args);
|
||
if (cmd == "fine-tune" || cmd == "finetune" || cmd == "sft" || cmd == "ft")
|
||
return cmd_fine_tune(args);
|
||
if (cmd == "chat" || cmd == "talk" || cmd == "dialog")
|
||
return cmd_chat(args);
|
||
if (cmd == "ollama" || cmd == "serve" || cmd == "server")
|
||
return cmd_ollama(args);
|
||
if (cmd == "update") return cmd_update(args);
|
||
if (cmd == "manifest") return cmd_manifest(args);
|
||
if (cmd == "shaders") return cmd_shaders(args);
|
||
if (cmd == "backends") return cmd_backends(args);
|
||
if (cmd == "convert" || cmd == "export" || cmd == "import" || cmd == "gguf")
|
||
return cmd_convert(args, /*type_required=*/false);
|
||
if (cmd == "quantize" || cmd == "quant" || cmd == "requantize")
|
||
return cmd_convert(args, /*type_required=*/true);
|
||
if (cmd == "dequantize" || cmd == "dequant")
|
||
return cmd_dequantize(args);
|
||
if (cmd == "agent-demo" || cmd == "agents")
|
||
return cmd_agent_demo(args);
|
||
if (cmd == "devices") {
|
||
if (!vulkan_available()) { printf("сборка без Vulkan\n"); return 1; }
|
||
auto devs = vulkan_list_devices();
|
||
if (devs.empty()) { printf("Vulkan-устройств не найдено\n"); return 1; }
|
||
for (auto& d : devs) printf("%s\n", d.c_str());
|
||
return 0;
|
||
}
|
||
|
||
fprintf(stderr, "неизвестная команда: %s\n\n", cmd.c_str());
|
||
printf("%s", HELP_TEXT.c_str());
|
||
return 1;
|
||
} |