Files
Xenith/main.cpp
T
2026-10-14 02:37:20 +07:00

639 lines
26 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.
#include "xenith/core/checkpoint.h"
#include "xenith/core/generate.h"
#include "xenith/core/train.h"
#include "xenith/core/gradcheck.h"
#include "xenith/core/dataset.h"
#include "xenith/ollama_api/handler.h"
#include <cstdio>
#include "help.h"
#include <cctype>
#include <cstdlib>
#include <algorithm>
#include <filesystem>
#include <string>
#include <vector>
#include <map>
#include <fstream>
#include <iostream>
#include <sstream>
#include <sys/stat.h>
namespace fs = std::filesystem;
namespace std::filesystem::__cxx11
{
class filesystem_error;
}
using namespace xt;
static std::string read_all(const std::string& p, bool& ok) {
std::ifstream f(p, std::ios::binary);
if (!f) { ok = false; return {}; }
std::ostringstream ss; ss << f.rdbuf(); ok = true; return ss.str();
}
static void mkdirs(const std::string& path) {
std::string cur;
for (size_t i = 0; i <= path.size(); ++i) {
if (i == path.size() || path[i] == '/') {
if (!cur.empty() && cur != ".") ::mkdir(cur.c_str(), 0755);
if (i == path.size()) break;
}
cur += path[i];
}
}
struct Version {
int major = 0;
int minor = 0;
int patch = 0;
};
struct Args {
std::map<std::string, std::string> kv;
std::vector<std::string> pos;
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 (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());
}
};
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; }
Checkpoint ck;
ck.seed = (uint64_t)a.geti("seed", 1337);
ck.params.cfg.vocab_size = a.geti("vocab", 512);
ck.params.cfg.n_embd = a.geti("embd", 128);
ck.params.cfg.n_layer = a.geti("layers", 4);
ck.params.cfg.n_head = a.geti("heads", 4);
ck.params.cfg.block_size = a.geti("ctx", 128);
ck.params.cfg.ffn_dim = a.geti("ffn", 0);
ck.params.cfg.rope_base = a.geti("rope", 10000);
// 0 = tied (выход делится с wte), -1 = untied (отдельная матрица lm_head).
// Раньше здесь стояло n_vocab_out = vocab_size, из-за чего tied() всё равно
// возвращал true и флаг --untied не делал ничего.
if (a.has("untied")) ck.params.cfg.n_vocab_out = -1;
ck.tok.build_from_text(text, ck.params.cfg.vocab_size, a.has("view-vocab"));
ck.params.cfg.vocab_size = ck.tok.size();
std::string err;
if (!ck.params.cfg.valid(err)) { fprintf(stderr, "new: плохая конфигурация: %s\n", err.c_str()); return 1; }
if (ck.tok.size() < 16) { fprintf(stderr, "new: корпус дал всего %d токенов, нужно больше текста\n", ck.tok.size()); return 1; }
ck.params.init(ck.seed);
printf("создаю модель: %s\n", out.c_str());
print_model_info(ck);
size_t slash = out.find_last_of('/');
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)) { fprintf(stderr, "train: %s\n", err.c_str()); return 1; }
TrainConfig tc;
tc.steps = a.geti("steps", 1000);
tc.batch_size = a.geti("batch", 8);
tc.block = a.geti("block", 64);
tc.lr = a.getf("lr", 3e-4f);
tc.weight_decay = a.getf("wd", 0.01f);
tc.clip = a.getf("clip", 1.0f);
tc.warmup = a.geti("warmup", 100);
tc.seed = (uint64_t)a.geti("seed", 1337);
tc.log_every = a.geti("log-every", 50);
tc.ckpt_every = a.geti("ckpt-every", 0);
tc.val_every = a.geti("val-every", 0);
tc.val_tokens = a.geti("val-tokens", 20000);
tc.threads = a.geti("threads", 0);
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);
train_model(ck.params, ck.tok, corpus, tc, out, resume);
return 0;
}
static int cmd_gen(const Args& a) {
if (a.pos.empty()) { fprintf(stderr, "gen: укажите файл модели\n"); return 1; }
Checkpoint ck;
std::string err;
if (!load_checkpoint(a.pos[0], ck, err)) { fprintf(stderr, "gen: %s\n", err.c_str()); return 1; }
GenConfig gc;
gc.max_new_tokens = a.geti("n", 200);
gc.temperature = a.getf("temp", 0.8f);
gc.top_k = a.geti("top-k", 40);
gc.top_p = a.getf("top-p", 0.95f);
gc.seed = a.geti("seed", -1);
gc.stream = !a.has("no-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;
std::string text = generate(ck.params, ck.tok, prompt, gc, &ids);
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; }
Checkpoint ck;
std::string err;
if (!load_checkpoint(a.pos[0], ck, err)) { fprintf(stderr, "info: %s\n", err.c_str()); return 1; }
printf("файл: %s\n", a.pos[0].c_str());
print_model_info(ck);
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;
}
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)) { 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)) { 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;
}
// --- настройки датасета ---
DatasetConfig dc;
if (!load_dataset_config(a.get("ds-conf"), dc, err)) {
fprintf(stderr, "fine-tune: %s\n", err.c_str()); return 1;
}
dc.verbose = true;
// --- настройки обучения ---
TrainConfig tc;
tc.steps = a.geti("steps", 3000);
tc.batch_size = a.geti("batch", 8);
tc.block = a.geti("block", 256);
tc.lr = a.getf("lr", 3e-5f); // на дообучении в 10 раз ниже претрейна
tc.weight_decay = a.getf("wd", 0.0f); // wd на SFT тянет веса к нулю без пользы
tc.clip = a.getf("clip", 1.0f);
tc.warmup = a.geti("warmup", 100);
tc.seed = (uint64_t)a.geti("seed", 1337);
tc.log_every = a.geti("log-every", 25);
tc.ckpt_every = a.geti("ckpt-every", 0);
tc.val_every = a.geti("val-every", 0);
tc.val_tokens = a.geti("val-tokens", 20000);
tc.threads = a.geti("threads", 0);
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();
if (a.has("no-mask")) ds.cfg.loss_mask = false;
if (a.has("mask")) ds.cfg.loss_mask = true;
if (a.has("user-loss")) { ds.cfg.loss_mask = true; ds.cfg.user_loss = true; }
tc.loss_mask = ds.cfg.loss_mask;
// флаг --resume: продолжить с сохранённого шага (Adam-state берётся из файла)
int resume = a.has("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 ? "да" : "нет");
TrainStats st = train_on_chat(ck.params, ck.tok, ds, tc, out, resume);
if (st.step == 0) { fprintf(stderr, "fine-tune: обучение не выполнилось\n"); return 1; }
printf("\nготово: %s (loss %.4f, шаг %d)\n", out.c_str(), st.loss, st.step);
printf("проверить: xenith chat %s\n", out.c_str());
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;
if (!load_checkpoint(a.pos[0], ck, err)) { fprintf(stderr, "chat: %s\n", err.c_str()); return 1; }
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;
}
GenConfig gc;
gc.max_new_tokens = a.geti("n", 256);
gc.temperature = a.getf("temp", 0.7f);
gc.top_k = a.geti("top-k", 40);
gc.top_p = a.getf("top-p", 0.9f);
gc.repeat_penalty = a.getf("repeat-penalty", 1.0f);
gc.seed = a.geti("seed", -1);
gc.stream = !a.has("no-stream");
const bool show_tokens = a.has("show-tokens");
const int threads = a.geti("threads", 0);
if (threads > 0) set_threads(threads);
const std::string sys = a.get("system", "Ты — ассистент Xenith. Отвечай кратко и по делу.");
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 out_ck{ck.params, ck.tok, turn, 0.0f, ck.seed};
std::string serr;
if (save_checkpoint(arg, out_ck, 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; }
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);
// предупреждение о переполнении контекста
if ((int)history.size() > ck.params.cfg.block_size * 3 / 4)
printf(" [i] история %zu/%d токенов — скоро начнёт обрезаться начало\n",
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.conf = a.get("conf", a.get("config"));
opt.port = a.geti("port", 11434);
opt.host = a.get("host", "127.0.0.1");
opt.default_model = a.get("model", a.get("default-model"));
opt.verbose = a.has("verbose") || a.has("v");
if (a.has("no-scan")) opt.scan_models_dir = false;
return run_ollama_server(opt);
}
Version parse_version(const std::string& str) {
Version v;
std::stringstream ss(str);
std::string segment;
try {
if (std::getline(ss, segment, '.')) v.major = std::stoi(segment);
else return v;
if (std::getline(ss, segment, '.')) v.minor = std::stoi(segment);
else return v;
if (std::getline(ss, segment, '.')) v.patch = std::stoi(segment);
} catch (const std::exception& e) {
std::cerr << "Ошибка парсинга версии '" << str << "': " << e.what() << std::endl;
}
return v;
}
// Правильное сравнение версий
bool is_newer(const Version& remote, const Version& current) {
if (remote.major != current.major) return remote.major > current.major;
if (remote.minor != current.minor) return remote.minor > current.minor;
return remote.patch > current.patch;
}
static bool available_new_version() {
const std::string REMOTE_URL = "https://git.bipfr.ru/BIPfR/Xenith/raw/branch/master/version.txt";
const std::string TMP_FILE = "./tmp/remote_version.txt";
fs::create_directories("./tmp");
std::string cmd = "curl -s --fail \"" + REMOTE_URL + "\" -o \"" + TMP_FILE + "\"";
int curl_result = system(cmd.c_str());
if (curl_result != 0) {
std::cerr << "Не удалось скачать версию. Проверьте интернет или URL." << std::endl;
return false;
}
std::ifstream tmp_file(TMP_FILE);
std::string remote_str = "0.0.0";
if (tmp_file.is_open() && std::getline(tmp_file, remote_str)) {
tmp_file.close();
} else {
std::cerr << "Файл версии пуст или нечитаем" << std::endl;
return false;
}
std::ifstream local_file("./version.txt");
std::string local_str = "0.0.0";
if (local_file.is_open() && std::getline(local_file, local_str)) {
local_file.close();
}
Version remote_ver = parse_version(remote_str);
Version local_ver = parse_version(local_str);
std::cout << "Локальная версия: " << local_ver.major << "."
<< local_ver.minor << "." << local_ver.patch << std::endl;
std::cout << "Удалённая версия: " << remote_ver.major << "."
<< remote_ver.minor << "." << remote_ver.patch << std::endl;
return is_newer(remote_ver, local_ver);
}
static int cmd_update(const Args& a) {
if (!available_new_version()) {
std::cout << "Уже установлена последняя версия!" << std::endl;
return 0;
}
std::cout << "Начинаем обновление..." << std::endl;
std::cout << "Очистка старых файлов (сохраняем models/)..." << std::endl;
for (const auto& entry : fs::directory_iterator(".")) {
std::string name = entry.path().filename().string();
if (name == "models") continue;
try {
if (fs::is_directory(entry.status())) {
fs::remove_all(entry.path());
} else {
fs::remove(entry.path());
}
} catch (const fs::filesystem_error& e) {
std::cerr << "Ошибка удаления " << name << ": " << e.what() << std::endl;
}
}
const std::string REPO_URL = "https://git.bipfr.ru/BIPfR/Xenith.git";
const std::string TMP_CLONE = "/tmp/xenith_update";
system(("rm -rf " + TMP_CLONE).c_str());
std::cout << "Скачивание новой версии..." << std::endl;
int result = system(("git clone --depth 1 " + REPO_URL + " " + TMP_CLONE).c_str());
if (result != 0) {
std::cerr << "Ошибка клонирования репозитория" << std::endl;
return -1;
}
std::cout << "Копирование файлов..." << std::endl;
result = system(("cp -ra " + TMP_CLONE + "/. .").c_str());
if (result != 0) {
std::cerr << "Ошибка копирования файлов" << std::endl;
system(("rm -rf " + TMP_CLONE).c_str());
return -1;
}
system(("rm -rf " + TMP_CLONE).c_str());
std::cout << "Обновление завершено!" << std::endl;
return 0;
}
int main(int argc, char** argv) {
if (argc < 2) { printf(HELP_TEXT.c_str()); return 1; }
const std::string cmd = argv[1];
if (cmd == "-h" || cmd == "--help" || cmd == "help") { printf(HELP_TEXT.c_str()); return 0; }
Args a(argc, argv, 2);
if (cmd == "new") return cmd_new(a);
if (cmd == "train") return cmd_train(a);
if (cmd == "gen") return cmd_gen(a);
if (cmd == "info") return cmd_info(a);
if (cmd == "gradcheck") return cmd_gradcheck(a);
if (cmd == "bench") return cmd_bench(a);
if (cmd == "fine-tune" || cmd == "finetune" || cmd == "sft" || cmd == "ft")
return cmd_fine_tune(a);
if (cmd == "chat" || cmd == "talk" || cmd == "dialog")
return cmd_chat(a);
if (cmd == "ollama" || cmd == "serve" || cmd == "server")
return cmd_ollama(a);
if (cmd == "update") return cmd_update(a);
fprintf(stderr, "неизвестная команда: %s\n\n", cmd.c_str());
printf(HELP_TEXT.c_str());
return 1;
}