20 Commits
Author SHA1 Message Date
KoDer bc582893cc Ollama AssistentChat BagFix 2026-10-14 02:37:20 +07:00
KoDer 18ca22aafc Merge branch 'master' of git.bipfr.ru resolving conflicts in favor of local changes 2026-10-13 23:39:59 +07:00
KoDer 447a78f553 ReBuild Bagfix 2026-10-13 23:38:27 +07:00
KoDer 1766a0f2e3 Merge remote-tracking branch 'origin/master' 2026-10-04 14:54:03 +07:00
KoDer 1fb0454ac3 fix 2026-10-04 14:53:49 +07:00
KoDer 0c065a0931 fix 2026-10-04 14:53:45 +07:00
KoDer 0d1bc4d936 --fast 2026-10-04 14:14:02 +07:00
KoDer 515a434928 Обновить README.md 2026-10-04 07:12:52 +00:00
KoDer 66048bff05 --fast 2026-10-04 14:09:29 +07:00
KoDer 9787b69588 --fast 2026-10-04 13:58:01 +07:00
KoDer f0c1d23121 --fast 2026-10-04 13:57:10 +07:00
KoDer ecf33beb01 Обновить README.md 2026-10-02 12:31:40 +00:00
KoDer 9e0f21023d Merge remote-tracking branch 'origin/master' 2026-10-02 19:31:02 +07:00
KoDer 87b45a1484 HPP 2026-10-02 19:30:49 +07:00
KoDer 14ae41d2db Обновить README.md 2026-10-02 05:29:43 +00:00
KoDer ecef2f41af TUI 2026-10-02 00:57:40 +07:00
KoDer a081d4d7e8 BugFix 2026-10-01 18:06:22 +07:00
KoDer 0dd3e46b6f BugFix 2026-10-01 17:55:04 +07:00
KoDer cf005944b8 BugFix 2026-10-01 17:53:20 +07:00
KoDer 35dfb8d3a5 Tui/OllamaApi 2026-10-01 01:59:58 +07:00
28 changed files with 3322 additions and 314 deletions

No files matched your search

+33 -12
View File
@@ -5,10 +5,13 @@ set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
set(CMAKE_CXX_FLAGS_DEBUG "-O1 -g -fsanitize=address,undefined")
set(CMAKE_EXE_LINKER_FLAGS_DEBUG "-fsanitize=address,undefined")
# дополняем дефолты CMake, а не перезаписываем их
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O1 -g -fsanitize=address,undefined")
set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} -fsanitize=address,undefined")
else()
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -ffast-math -funroll-loops")
# БЕЗ -ffast-math: он разрешает перестановку float-сложений, из-за чего
# gradcheck и softmax становятся недетерминированными.
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O3 -funroll-loops")
endif()
add_compile_options(-Wall -Wextra -Wno-unused-parameter)
@@ -21,16 +24,20 @@ set(SOURCES
xenith/core/checkpoint.cpp
xenith/core/generate.cpp
xenith/core/gradcheck.cpp
# Файлы, которые уже были в твоем старом CMakeLists.txt
xenith/preprocessing/tokenizer.cpp
xenith/ollama_api/test.cpp
xenith/converter.cpp
help.h
xenith/core/dataset.cpp
# Ollama-совместимый HTTP-сервер
xenith/ollama_api/handler.cpp
xenith/ollama_api/handler.h
xenith/ollama_api/server.h
)
# xenith/preprocessing/tokenizer.cpp и xenith/converter.cpp НЕ собираются:
# это мёртвое ядро старого формата .bfr, на него никто не ссылается, а
# tokenizer.h включает models/test_model.h, которого нет в репозитории
# (каталог models/ в .gitignore). Вернёшь — сначала починь этот include.
# ВНИМАНИЕ: xenith/ollama_api/test.cpp здесь НЕ listed — в нём собственный main(),
# из-за которого линковка падала с "multiple definition of main". Он собирается
# отдельным таргетом xenith_ollama_mock ниже.
# Заголовочные файлы (для удобства в IDE)
file(GLOB_RECURSE HEADER_FILES "*.h" "*.hpp")
@@ -41,6 +48,20 @@ add_executable(Xenith ${SOURCES} ${HEADER_FILES})
# Настройка include директорий
target_include_directories(Xenith PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
# Потоки (pthread)
# Потоки (pthread) — нужны и ядру, и cpp-httplib
find_package(Threads REQUIRED)
target_link_libraries(Xenith PRIVATE Threads::Threads)
target_link_libraries(Xenith PRIVATE Threads::Threads)
# cpp-httplib в режиме сервера требует сокет-библиотеку Windows; на Linux достаточно pthread
if(WIN32)
target_link_libraries(Xenith PRIVATE ws2_32 crypt32)
endif()
# --- необязательный таргет: мок Ollama-сервера для ручных проверок ---
# Собирается только если у файла починены include-пути до nlohmann/json.
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/xenith/ollama_api/test.cpp)
add_executable(xenith_ollama_mock xenith/ollama_api/test.cpp)
target_include_directories(xenith_ollama_mock PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/xenith)
target_link_libraries(xenith_ollama_mock PRIVATE Threads::Threads)
set_target_properties(xenith_ollama_mock PROPERTIES EXCLUDE_FROM_ALL TRUE)
endif()
+360 -48
View File
@@ -1,48 +1,106 @@
# Xenith
[![Platform](https://img.shields.io/badge/platform-Linux-blue)]()
[![C++](https://img.shields.io/badge/C++-20-blue)]()
[![C++](https://img.shields.io/badge/C++-17-blue)]()
[![Лицензия](https://img.shields.io/badge/license-MIT-green)]()
Трансформер на чистом C++: обучение и генерация текста на CPU, без внешних
зависимостей. Всё в одном бинарнике.
Трансформер на чистом C++: обучение, дообучение на диалогах и генерация текста на CPU,
без внешних зависимостей. Всё в одном бинарнике + HTTP-сервер, совместимый с Ollama API.
## Что внутри
Архитектура — как у LLaMA: pre-norm, RMSNorm, RoPE, SwiGLU, связанные
эмбеддинги (tied weights), каузальное внимание. Обучение — вручную
написанный обратный проход + AdamW. Никаких фреймворков.
Архитектура — как у LLaMA: pre-norm, RMSNorm, RoPE, SwiGLU, связанные эмбеддинги
(tied weights), каузальное внимание. Обучение — вручную написанный обратный проход
+ AdamW. Никаких фреймворков.
| файл | что делает |
|---|---|
| `xenith/core/tensor.h` | матрицы, три формы GEMM, RMSNorm, RNG, пул потоков |
| `xenith/core/model.cpp` | конфигурация, инициализация, прямой проход, RoPE, Adam |
| `xenith/core/backward.cpp` | обратный проход (ручной, без автомиффов) |
| `xenith/core/backward.cpp` | обратный проход (ручной) + **маска loss для SFT** |
| `xenith/core/trainer.cpp` | цикл обучения, расписание lr, чекпоинты, валидация |
| `xenith/core/generate.cpp` | генерация с KV-кэшем, temperature / top-k / top-p |
| `xenith/core/dataset.cpp` | **разбор JSON-датасета диалогов → токены + маска** |
| `xenith/core/generate.cpp` | генерация с KV-кэшем, temperature / top-k / top-p, **chat_turn** |
| `xenith/core/checkpoint.cpp` | формат `.xnh`, токенизатор, сохранение/загрузка |
| `xenith/core/gradcheck.cpp` | численная проверка градиентов + бенчмарк |
| `xenith/ollama_api/handler.cpp` | **HTTP-сервер Ollama API** |
## Сборка
```bash
cmake -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -j
# бинарник: bin/Xenith
```
Debug-сборка включает AddressSanitizer и UndefinedBehaviorSanitizer.
Release собирается **без** `-ffast-math` намеренно: он разрешает перестановку
float-сложений, из-за чего `gradcheck` и softmax становятся недетерминированными.
## Спецтокены
Словарь любой модели Xenith начинается с шести зарезервированных токенов:
| id | токен | назначение |
|---|---|---|
| 0 | `<unk>` | символ, которого нет в словаре |
| 1 | `<bos>` | начало последовательности |
| 2 | `<eos>` | **конец реплики** — по нему останавливается чат |
| 3 | `<user>` | маркер реплики пользователя |
| 4 | `<assistant>` | маркер реплики ассистента |
| 5 | `\n` | перевод строки |
Дальше идут частые слова, затем уникальные UTF-8 символы. Словарь двухуровневый:
частые слова берутся целиком, остальное режется на символы — любой текст кодируется
без потерь, но это не BPE.
Формат модели — `.xnh`, **версия 2** (старые файлы версии 1 читаются, но чат с ними
не работает: в их словаре нет `<user>`/`<assistant>`).
## Быстрый старт
### А. Продолжатель текста (как раньше)
```bash
# 1) собрать модель из своего текста
./bin/Xenith new models/my.xnh --corpus data.txt \
--vocab 512 --embd 128 --layers 6 --heads 8 --ctx 256
--vocab 4096 --embd 256 --layers 6 --heads 8 --ctx 512
# 2) обучить
./bin/Xenith train models/my.xnh --corpus data.txt \
--out models/my_trained.xnh --steps 5000 --batch 16 --lr 3e-4
--out models/my_trained.xnh --steps 20000 --batch 8 --block 256 --lr 3e-4
# 3) сгенерировать
./bin/Xenith gen models/my_trained.xnh --prompt "Привет" --n 200 --temp 0.8
```
### Б. Диалоговая модель
```bash
# 1) модель — обязательно с запасом по контексту: --ctx это потолок длины диалога
./bin/Xenith new models/chat.xnh --corpus corpus.txt \
--vocab 4096 --embd 256 --layers 6 --heads 8 --ctx 512
# 2) дообучение на JSON-датасете диалогов
./bin/Xenith fine-tune models/chat.xnh --data dialog.json \
--ds-conf dataset.conf.json --out models/chat_ft.xnh \
--steps 4000 --batch 8 --block 256 --lr 3e-5 --wd 0.0 --resume
# 3) разговор
./bin/Xenith chat models/chat_ft.xnh
```
`corpus.txt` для шага 1 — это **текст реплик**, а не JSON целиком: иначе ключи
`"role"`, `"content"`, `"messages"` и фигурные скобки попадут в словарь как паразитные
токены. Вытащить их из датасета можно так:
```bash
jq -r '.[].messages[].content' dialog.json > corpus.txt
```
## Команды
### new — создать модель
Читает корпус, строит по нему словарь, инициализирует веса случайно.
### `new` — создать модель
```
--corpus PATH текст (обязательно)
@@ -51,7 +109,7 @@
--embd N ширина эмбеддинга (128)
--layers N число слоёв (4)
--heads N число голов (4). embd должен делиться на heads
--ctx N максимальный контекст (128)
--ctx N максимальный контекст (128) — для чата ставь 512+
--ffn N ширина FFN (0 = 4*embd)
--rope N база RoPE (10000)
--seed N зерно инициализации (1337)
@@ -59,11 +117,7 @@
--view-vocab вывести словарь нейросети
```
Словарь двухуровневый: частые слова берутся целиком, остальное режется на
символы. Так словарь остаётся маленьким, а любой текст кодируется без потерь —
модель может учить и слова, и буквы.
### train — обучить
### `train` — обучение на сплошном тексте
```
--corpus PATH текст (обязательно)
@@ -84,34 +138,166 @@
--resume продолжить с сохранённого step
```
Прогрев + косинусное затухание до `lr * 0.1`. Промежуточные чекпоинты
пишутся как `models/my.xnh.step1500` — можно откатиться, если loss
развалился.
Прогрев + косинусное затухание до `lr * 0.1`. Промежуточные чекпоинты пишутся как
`models/my.xnh.step1500` — можно откатиться, если loss развалился.
### gen — сгенерировать
### `fine-tune` — дообучение на диалогах
Принимает JSON-датасет и учит модель **отвечать**, а не продолжать текст.
```
<модель.xnh> что дообучаем (обязательно)
--data PATH JSON-датасет диалогов (обязательно)
--ds-conf PATH JSON с настройками разбора датасета
--out PATH куда сохранить (по умолчанию перезапись входного файла)
--steps N шагов (3000)
--batch N батч (8)
--block N длина окна (256; урезается до ctx модели)
--lr F скорость (3e-5 — в 10 раз ниже претрейна)
--wd F weight decay (0.0)
--warmup N прогрев (100)
--clip F клип нормы градиента (1.0)
--mask loss только на репликах ассистента (вкл по умолчанию)
--no-mask loss по всем позициям, как в обычном train
--user-loss учить также реплики пользователя
--resume продолжить с сохранённого step (Adam-state из файла)
--ckpt-every N промежуточное сохранение (0)
--val-every N валидация каждые N шагов (0)
--log-every N как часто печатать (25)
--threads N потоков (0 = все ядра)
```
Почему именно такие значения по умолчанию:
| параметр | претрейн | fine-tune | причина |
|---|---|---|---|
| `--lr` | 3e-4 | **3e-5** | иначе катастрофическое забывание базовых знаний |
| `--wd` | 0.01 | **0.0** | weight decay на дообучении тянет веса к нулю без пользы |
| `--block` | 64 | **256** | диалог не влезает в 64 токена |
| `--resume` | — | **обязательно** | подтягивает Adam-state (`m`, `v`) из чекпоинта |
### `chat` — интерактивный диалог
Бесконечный цикл «запрос → ответ». История живёт между ходами, поэтому диалог
многоходовой. Ответ обрывается на `<eos>`.
```
<модель.xnh> модель с маркерами <user>/<assistant> (обязательно)
--system STR системная установка
--no-system без системной установки
--n N максимум токенов в ответе (256)
--temp F температура, 0 = жадный выбор (0.7)
--top-k N top-k (40, 0 = выкл)
--top-p F top-p (0.9, 1.0 = выкл)
--repeat-penalty F штраф за повторы (1.0 = выкл)
--seed N зерно (по умолчанию от часов)
--no-stream печатать ответ целиком
--show-tokens показывать id токенов и причину останова
--threads N потоков (0 = все ядра)
```
Команды внутри диалога:
| команда | действие |
|---|---|
| `/exit`, `/quit`, `/q` | выйти |
| `/reset` | очистить историю (новый диалог) |
| `/history` | история в токенах + её текст |
| `/save <путь.xnh>` | сохранить текущие веса |
| `/model` | конфигурация модели |
| `/temp <f>`, `/n <int>` | поменять настройки на лету |
| `/help` | список команд |
Если модель выдала `<user>` — генерация прерывается и печатается предупреждение:
значит, она отвечает за обе роли (нужна маска loss и/или больше данных).
### `gen` — продолжение текста
```
--prompt STR стартовый текст
--n N сколько токенов (200)
--temp F температура; 0 = жадный выбор (0.8)
--top-k N top-k (40), 0 = выкл
--top-p F top-p (0.95), 1.0 = выкл
--seed N зерно
--temp F температура, 0 = жадный выбор (0.8)
--top-k N top-k (40, 0 = выкл)
--top-p F top-p (0.95, 1.0 = выкл)
--repeat-penalty F штраф за повторы (1.0)
--seed N зерно (по умолчанию от часов)
--no-stream не печатать в процессе
--batch "a;b;c" несколько промптов через ;
--show-tokens показать id токенов
```
### ollama — сгенерировать
### `ollama` — HTTP-сервер с Ollama API
```
--port PORT порт сервера (по умолчанию 11434)
--conf NAME.conf конфиг с настройками и списком моделей
--port PORT порт (11434)
--host ADDR адрес (127.0.0.1; 0.0.0.0 — слушать всех)
--conf NAME.conf JSON-конфиг
--model NAME модель по умолчанию
--no-scan не подхватывать models/*.xnh автоматически
--verbose печатать каждый запрос
```
### update - проверка обновления
Конфиг (`ollama.conf`):
### info / gradcheck / bench
```json
{
"host": "127.0.0.1",
"port": 11434,
"default_model": "bipy",
"scan_models_dir": true,
"verbose": false,
"models": [ { "name": "bipy", "path": "models/bipy.xnh" } ]
}
```
Если конфига нет, сервер сам сканирует `./models/*.xnh`. Модель грузится лениво —
при первом обращении — и остаётся в памяти.
#### Эндпоинты
| метод | путь | что делает |
|---|---|---|
| GET | `/api/version` | версия Xenith |
| GET | `/api/tags` | список моделей (формат Ollama) |
| GET | `/api/ps` | загруженные модели + размер в VRAM |
| POST | `/api/show` | параметры, шаблон, modelfile, capabilities |
| POST | `/api/create` | регистрация модели: `{"model":"имя","modelfile":"FROM models/x.xnh"}` |
| POST | `/api/delete` | выгрузка модели из реестра |
| POST | `/api/generate` | генерация продолжения, `stream: true/false` |
| POST | `/api/chat` | диалог в формате `messages`, `stream: true/false` |
| POST | `/api/embed` | эмбеддинги: среднее `wte` по токенам, L2-нормировка |
| POST | `/api/embeddings` | то же, старый формат Ollama |
| GET | `/` | служебная страница со списком моделей |
| GET | `/health` | проверка живости |
| POST | `/api/pull`, `/api/push`, GET `/api/blobs/:digest` | **501** — реестра моделей у Xenith нет |
Поддерживаемые `options`: `temperature`, `num_predict`, `seed`, `top_k`, `top_p`,
`repeat_penalty`, `stop` (строка или массив). `num_predict: -1` — без лимита.
```bash
curl http://localhost:11434/api/tags
curl http://localhost:11434/api/chat -d '{
"model": "bipy", "stream": false,
"messages": [{"role":"user","content":"привет"}]}'
curl http://localhost:11434/api/generate -d '{
"model": "bipy", "prompt": "Привет", "stream": false,
"options": {"temperature": 0.7, "num_predict": 64}}'
curl http://localhost:11434/api/embed -d '{"model":"bipy","input":["привет","мир"]}'
curl http://localhost:11434/api/create -d '{
"model":"my","modelfile":"FROM models/chat_ft.xnh"}'
```
Стриминг настоящий: генерация идёт в отдельном потоке, чанки NDJSON уходят по мере
появления. При разрыве соединения взводится флаг отмены и генерация прерывается.
⚠️ Ядро Xenith однопоточное и не потокобезопасное, поэтому все запросы на генерацию
сериализуются одним мьютексом — сервер обрабатывает один запрос за раз.
### `info` / `gradcheck` / `bench`
```bash
./bin/Xenith info models/my.xnh # конфигурация и словарь
@@ -122,24 +308,150 @@
`gradcheck` стоит запускать после любой правки в `model.cpp` / `backward.cpp` —
он ловит ошибку в обратном проходе за секунды.
## Формат модели
## Формат JSON-датасета
Один файл `.xnh` содержит и словарь, и веса, и состояние оптимизатора.
При загрузке проверяется каждая размерность тензора, так что модель,
собранная с другими настройками, отвергается с понятной ошибкой, а не
молча портит вывод.
Основной формат (OpenAI-совместимый):
Совместимость с `models/test_model.bfr` (старый формат) **не** поддерживается:
там была другая раскладка весов.
```json
[
{
"messages": [
{ "role": "user", "content": "Где ты сейчас находишься?" },
{ "role": "assistant", "content": "Лежу утром в постели, на своей квартире." }
]
},
{
"messages": [
{ "role": "user", "content": "Как ты себя чувствуешь?" },
{ "role": "assistant", "content": "Мысль гуляет вольной птицей по лицу." }
]
}
]
```
Также принимаются:
```json
{ "data": [ { "messages": [...] } ] }
[ [ {"role":"user","content":"…"}, {"role":"assistant","content":"…"} ] ]
[ { "conversations": [ {"from":"human","value":"…"}, {"from":"gpt","value":"…"} ] } ]
```
Роли нормализуются: `human`/`человек`/`q` → `user`, `gpt`/`bot`/`ai`/`bipy`/`xenith` → `assistant`.
**Роль `system` пропускается** — отдельного токена `<system>` в словаре нет.
Системный промпт приклеивается к реплике пользователя (в `chat` — через `--system`,
в сервере — автоматически из `messages`).
Каждый пример превращается в последовательность:
```
<bos> <user> [вопрос] <assistant> [ответ] <eos>
```
### Настройки разбора — `dataset.conf.json`
```json
{
"block": 256,
"pack_mode": 0,
"loss_mask": true,
"user_loss": false,
"learn_marker": true,
"learn_eos": true,
"min_chars": 2,
"allow_dangling_user": true,
"strict": false,
"verbose": true
}
```
| ключ | что делает |
|---|---|
| `block` | длина обучающего окна; урезается до `ctx` модели |
| `pack_mode` | `0` — склеить всё в поток и нарезать окна; `1` — один диалог на строку батча |
| `loss_mask` | `true` — учить только реплики ассистента |
| `user_loss` | `true` — учить ещё и реплики пользователя |
| `learn_marker` | `true` — учить модель выдавать `<assistant>` (без этого она не знает, когда начинать ответ) |
| `learn_eos` | `true` — учить останавливаться (без этого генерация не обрывается) |
| `min_chars` | реплики короче этого пропускаются |
| `allow_dangling_user` | брать ли диалоги, обрывающиеся на реплике пользователя |
| `strict` | любая ошибка парсинга прерывает работу |
| `verbose` | печатать статистику разбора |
## Как работает маска loss
`mask[i] == 1` означает «позиция `i` учится предсказывать `ids[i+1]`».
```
idx : 0 1 2 … k-1 k k+1 … m-1 m
id : <bos> <user> ▸ … ▸ <assistant> ▸ … ▸ <eos>
mask: 0 0 0 … 1 1 1 … 1 0
↑ learn_marker ↑ learn_eos
```
- перед `<user>` маска **всегда** 0 — иначе модель учится задавать вопросы сама себе;
- перед `<assistant>` маска 1 (`learn_marker`) — модель учится начинать ответ;
- перед `<eos>` маска 1 (`learn_eos`) — модель учится заканчивать реплику;
- нормировка loss идёт на число активных позиций, а не на размер батча, иначе
эффективный lr плавает от состава батча.
Маска **не** убирает пользовательские токены из модели: они по-прежнему проходят
через forward и видны attention'у ассистентских позиций. Отключается только
обратный поток. Модель учится *использовать* вопрос, но не *порождать* его.
## Что учесть
- **Скорость.** ~7600 ток/с на 4 ядрах для 4 слоёв × 64 измерения. С ростом
модели скорость падает квадратично по `embd` и линейно по слоям.
Замеряйте своим `bench`.
- **Форма входа.** `text`, `code`, `html` — чем однороднее корпус, тем
меньше словарь и тем быстрее обучение.
- **Количество данных.** Модель на 0.25 млн параметров хочет хотя бы
несколько мегабайт текста, иначе будет только запоминать.
- **Токенизатор** — слова + символы, не BPE. Для морфологически богатых
языков это проще, но экономнее BPE приходится платить длиной последовательности.
- **Контекст — это потолок диалога.** `--ctx` фиксируется при `new` и лежит в чекпоинте,
поднять его дообучением нельзя. При переполнении история обрезается с начала,
то есть модель забывает системный промпт и первые ходы. Для чата нужно 512+.
- **Ёмкость.** Модель на 0.25 млн параметров выучит формат и будет выдавать
заученные реплики по триггеру, а не «вести диалог». Для вменяемого поведения
нужно 5-20 млн параметров и тысячи разнообразных диалогов.
- **Чем меньше модель, тем жёстче формат.** Одна и та же разметка во всём датасете,
без вариантов `User:` / `Q:` / `—`.
- **`--block` должен быть не короче самого длинного диалога.** Иначе примеры
отбрасываются — смотри строку «отброшено длинных» в отчёте `fine-tune`.
- **Скорость.** ~7600 ток/с на 4 ядрах для 4 слоёв × 64 измерения. С ростом модели
скорость падает квадратично по `embd` и линейно по слоям. Замеряйте своим `bench`.
- **Пробелы не кодируются.** Токенизатор разбирает текст по пробельным символам и
сами пробелы не сохраняет; при декодировании пробел восстанавливается после каждого
многосимвольного токена. Следствие: `"кот пёс"` и `"кот пёс"` кодируются одинаково.
Для диалога это не мешает (маркеры — одиночные токены), но знать стоит.
## Формат модели
Один файл `.xnh` содержит словарь, веса и состояние оптимизатора. При загрузке
проверяется каждая размерность тензора, так что модель, собранная с другими
настройками, отвергается с понятной ошибкой, а не молча портит вывод.
Версия 1 (старая раскладка `<unk> <bos> <eos> \n`) читается, но `chat` и `fine-tune`
с ней не работают — в словаре нет маркеров. Совместимость с `models/test_model.bfr`
(старый формат `.bfr`) **не** поддерживается.
## Отладка
```bash
./bin/Xenith info models/chat.xnh # 0=<unk> 1=<bos> 2=<eos> 3=<user> 4=<assistant> 5=\n
./bin/Xenith gen models/chat.xnh --prompt "привет" --show-tokens --n 32
./bin/Xenith chat models/chat.xnh --show-tokens --temp 0.7
./bin/Xenith gradcheck --verbose
```
| симптом | причина |
|---|---|
| `fine-tune: в словаре нет <user>/<assistant>` | модель создана до обновления токенизатора → пересоздать через `new` |
| чат не останавливается, упирается в `--n` | в датасете не было `<eos>` на реплику, либо `learn_eos: false` |
| модель отвечает за обе роли | нет маски loss (`--mask`) или мало данных |
| «отброшено длинных» > 0 | подними `--block` и `--ctx` |
| «символов потеряно» много | `--vocab` мал для этого текста |
| ответ обрывается на первом слове | `<eos>` попал внутрь реплики — проверь, что датасет не содержит маркеров текстом |
## `update` — автообновление
```bash
./bin/Xenith update
```
⚠️ Команда удаляет **всё содержимое текущего каталога**, кроме `models/`, затем
клонирует репозиторий заново. Запускай только из каталога с установленным Xenith.
+80
View File
@@ -0,0 +1,80 @@
# _xenith - Zsh completion function for Xenith
_xenith() {
local curcontext="$curcontext" state line
typeset -A opt_args
local commands=(
'new:создать новую модель из корпуса'
'train:обучить существующую модель'
'gen:сгенерировать текст'
'info:показать конфигурацию модели'
'gradcheck:проверить градиенты численно'
'bench:замерить скорость форварда и шага обучения'
'update:автоматическое обновление с гита'
'tui:графическо-консольный режим (тест)'
)
_arguments -C \
'1: :->command' \
'*:: :->args' && return 0
case $state in
command)
_describe -t commands 'команды Xenith' commands
;;
args)
case $line[1] in
new)
_arguments \
'--corpus[текст для построения словаря]:файл:_files' \
'--out[файл модели]:файл:_files -g "*.xnh"' \
'--vocab[размер словаря]' \
'--embd[размер эмбеддинга]' \
'--layers[число слоёв]' \
'--heads[число голов внимания]' \
'--ctx[максимальный контекст]' \
'--ffn[размер FFN]' \
'--rope[база RoPE]' \
'--seed[зерно инициализации]' \
'--untied[использовать отдельную матрицу выхода]' \
'--view-vocab[вывести словарь нейросети]'
;;
train)
_arguments \
'--corpus[обучающий текст]:файл:_files' \
'--out[куда сохранить]:файл:_files -g "*.xnh"' \
'--steps[количество шагов обучения]' \
'--batch[размер батча]' \
'--block[длина окна контекста]' \
'--lr[скорость обучения]' \
'--wd[weight decay]' \
'--clip[клиппинг нормы градиента]' \
'--warmup[шаги прогрева]' \
'--seed[зерно генератора]' \
'--ckpt-every[сохранять чекпоинт каждые N шагов]' \
'--val-every[валидация каждые N шагов]' \
'--val-tokens[размер валидационной выборки]' \
'--threads[количество потоков (0 = все ядра)]' \
'--resume[продолжить обучение с последнего чекпоинта]' \
'--fast[экспериментальный флаг ускорения forward pass]'
;;
gen)
_arguments \
'--prompt[стартовый текст]' \
'--n[количество генерируемых токенов]' \
'--temp[температура выборки (0 = жадный)]' \
'--top-k[top-k sampling]' \
'--top-p[top-p nucleus sampling]' \
'--seed[зерно генератора]' \
'--no-stream[не печатать токены по мере генерации]' \
'--batch[несколько промптов через ;]' \
'--show-tokens[показывать ID токенов]'
;;
info|gradcheck|bench|update|tui)
_arguments \
'--fast[экспериментальный флаг ускорения]'
;;
esac
;;
esac
}
if [[ "$funcstack[1]" == "_xenith" ]]; then
_xenith "$@"
fi
+85
View File
@@ -0,0 +1,85 @@
set -gx VIRTUAL_ENV_PROMPT "Xenith"
complete -c Xenith -erase
complete -c ./bin/Xenith -erase
complete -c Xenith -f
complete -c ./bin/Xenith -f
set -l main_commands "new:создать новую модель из корпуса" \
"train:обучить существующую модель" \
"gen:сгенерировать текст" \
"info:показать конфигурацию модели" \
"gradcheck:проверить градиенты численно" \
"bench:замерить скорость форварда и шага обучения" \
"update:Автомотическое обновление с гита"
for cmd in $main_commands
set -l parts (string split ":" $cmd)
complete -c Xenith -n "__fish_use_subcommand" -a $parts[1] -d $parts[2]
complete -c ./bin/Xenith -n "__fish_use_subcommand" -a $parts[1] -d $parts[2]
end
set -l new_cond "__fish_seen_subcommand_from new"
complete -c Xenith -n $new_cond -l corpus -r -F -d "текст для построения словаря (обязательно)"
complete -c Xenith -n $new_cond -l out -r -F -d "файл модели (по умолчанию model.xnh)"
complete -c Xenith -n $new_cond -l vocab -r -d "размер словаря (по умолчанию 512)"
complete -c Xenith -n $new_cond -l embd -r -d "размер эмбеддинга (по умолчанию 128)"
complete -c Xenith -n $new_cond -l layers -r -d "число слоёв (по умолчанию 4)"
complete -c Xenith -n $new_cond -l heads -r -d "число голов (по умолчанию 4)"
complete -c Xenith -n $new_cond -l ctx -r -d "максимальный контекст (по умолчанию 128)"
complete -c Xenith -n $new_cond -l ffn -r -d "размер FFN (по умолчанию 4*embd)"
complete -c Xenith -n $new_cond -l rope -r -d "база RoPE (по умолчанию 10000)"
complete -c Xenith -n $new_cond -l seed -r -d "зерно инициализации (по умолчанию 1337)"
complete -c Xenith -n $new_cond -l untied -d "отдельная матрица выхода вместо привязанной к wte"
complete -c Xenith -n $new_cond -l view-vocab -d "выводит словарь нейросети"
set -l train_cond "__fish_seen_subcommand_from train"
complete -c Xenith -n $train_cond -l corpus -r -F -d "обучающий текст (обязательно)"
complete -c Xenith -n $train_cond -l out -r -F -d "куда сохранить (по умолчанию перезапись входного файла)"
complete -c Xenith -n $train_cond -l steps -r -d "шагов (по умолчанию 1000)"
complete -c Xenith -n $train_cond -l batch -r -d "батч (по умолчанию 8)"
complete -c Xenith -n $train_cond -l block -r -d "длина окна (по умолчанию 64)"
complete -c Xenith -n $train_cond -l lr -r -d "скорость (по умолчанию 3e-4)"
complete -c Xenith -n $train_cond -l wd -r -d "weight decay (по умолчанию 0.01)"
complete -c Xenith -n $train_cond -l clip -r -d "клип нормы градиента (по умолчанию 1.0)"
complete -c Xenith -n $train_cond -l warmup -r -d "прогрев (по умолчанию 100)"
complete -c Xenith -n $train_cond -l seed -r -d "зерно (по умолчанию 1337)"
complete -c Xenith -n $train_cond -l ckpt-every -r -d "промежуточное сохранение каждые N шагов"
complete -c Xenith -n $train_cond -l val-every -r -d "валидация каждые N шагов"
complete -c Xenith -n $train_cond -l val-tokens -r -d "размер валидации (по умолчанию 20000)"
complete -c Xenith -n $train_cond -l threads -r -d "потоков (0 = все ядра)"
complete -c Xenith -n $train_cond -l resume -d "продолжить с сохранённого step (Adam-state из файла)"
set -l gen_cond "__fish_seen_subcommand_from gen"
complete -c Xenith -n $gen_cond -l prompt -r -d "стартовый текст"
complete -c Xenith -n $gen_cond -l n -r -d "сколько токенов (по умолчанию 200)"
complete -c Xenith -n $gen_cond -l temp -r -d "температура, 0 = жадный выбор (по умолчанию 0.8)"
complete -c Xenith -n $gen_cond -l top-k -r -d "top-k (0 = выкл)"
complete -c Xenith -n $gen_cond -l top-p -r -d "top-p (1.0 = выкл)"
complete -c Xenith -n $gen_cond -l seed -r -d "зерно"
complete -c Xenith -n $gen_cond -l no-stream -d "не печатать в процессе"
complete -c Xenith -n $gen_cond -l batch -r -d "несколько промптов через ;"
complete -c Xenith -n $gen_cond -l show-tokens -d "показать id токенов"
complete -c ./bin/Xenith -n "__fish_seen_subcommand_from new" -a "(complete -C'Xenith new ')"
complete -c ./bin/Xenith -n "__fish_seen_subcommand_from train" -a "(complete -C'Xenith train ')"
complete -c ./bin/Xenith -n "__fish_seen_subcommand_from gen" -a "(complete -C'Xenith gen ')"
function Xenith
./bin/Xenith $argv
end
if not set -q _OLD_VIRTUAL_PS1
functions -c fish_prompt _old_fish_prompt
function fish_prompt
echo -n "($VIRTUAL_ENV_PROMPT) "
_old_fish_prompt
end
set -g _OLD_VIRTUAL_PS1 1
end
echo "Xenith activate"
function deactivate
functions -e Xenith
if functions -q _old_fish_prompt
functions -e fish_prompt
functions -c _old_fish_prompt fish_prompt
functions -e _old_fish_prompt
end
set -e VIRTUAL_ENV_PROMPT
set -e _OLD_VIRTUAL_PS1
complete -c Xenith -erase
complete -c ./bin/Xenith -erase
functions -e deactivate
echo "Xenith deactivated"
end
+21
View File
@@ -0,0 +1,21 @@
export VIRTUAL_ENV_PROMPT="\033[31mXenith\033[39m"
alias Xenith='./bin/Xenith'
if [ -z "${_OLD_VIRTUAL_PS1+x}" ]; then
_OLD_VIRTUAL_PS1="$PS1"
fi
PS1="($VIRTUAL_ENV_PROMPT) $_OLD_VIRTUAL_PS1"
deactivate_custom() {
unalias Xenith 2>/dev/null
unalias deactivate 2>/dev/null
if [ -n "${_OLD_VIRTUAL_PS1+x}" ]; then
PS1="$_OLD_VIRTUAL_PS1"
unset _OLD_VIRTUAL_PS1
fi
if (( $+functions[_old_virtual_deactivate] )); then
_old_virtual_deactivate
elif (( $+functions[deactivate] )); then
builtin deactivate 2>/dev/null || true
fi
unset -f deactivate_custom
}
alias deactivate='deactivate_custom'
+27
View File
@@ -0,0 +1,27 @@
# activate.zsh
export VIRTUAL_ENV_PROMPT="%F{red}Xenith%f"
alias Xenith='./bin/Xenith'
if [ -z "${_OLD_VIRTUAL_PS1+x}" ]; then
_OLD_VIRTUAL_PS1="$PS1"
fi
PS1="(${VIRTUAL_ENV_PROMPT}) ${_OLD_VIRTUAL_PS1}"
deactivate_custom() {
unalias Xenith 2>/dev/null
unalias deactivate 2>/dev/null
if [ -n "${_OLD_VIRTUAL_PS1+x}" ]; then
PS1="$_OLD_VIRTUAL_PS1"
unset _OLD_VIRTUAL_PS1
fi
if (( $+functions[_old_virtual_deactivate] )); then
_old_virtual_deactivate
elif (( $+functions[deactivate] )); then
builtin deactivate 2>/dev/null || true
fi
unset -f deactivate_custom
compdel Xenith 2>/dev/null
compdel ./bin/Xenith 2>/dev/null
}
alias deactivate='deactivate_custom'
source "${0:A:h}/_xenith"
compdef _xenith Xenith
compdef _xenith ./bin/Xenith
BIN
View File
Binary file not shown.
+18
View File
@@ -0,0 +1,18 @@
Где ты сейчас находишься и что делаешь?
Лежу утром в постели, на своей квартире, в Гороховой улице, в одном из больших домов.
Как ты себя чувствуешь? О чем думаешь?
Мысль гуляет вольной птицей по лицу, порхает в глазах, прячется в складках лба, а потом совсем пропадает. Во всем лице теплится ровный свет беспечности.
Привет
Привет! Чем могу помочь?
Сколько будет два плюс два?
Четыре.
Кто ты?
Я Xenith — маленькая языковая модель, собранная на чистом C++.
Что ты умеешь?
Отвечать на вопросы, продолжать текст и работать через Ollama API.
Расскажи про себя
Я трансформер на LLaMA-архитектуре: RMSNorm, RoPE, SwiGLU.
Как тебя зовут?
Меня зовут BiPy.
А что это значит?
Это название компании, которая меня собрала.
+12
View File
@@ -0,0 +1,12 @@
{
"block": 256,
"pack_mode": 0,
"loss_mask": true,
"user_loss": false,
"learn_marker": true,
"learn_eos": true,
"min_chars": 2,
"allow_dangling_user": true,
"strict": false,
"verbose": true
}
+90
View File
@@ -0,0 +1,90 @@
[
{
"messages": [
{
"role": "user",
"content": "Где ты сейчас находишься и что делаешь?"
},
{
"role": "assistant",
"content": "Лежу утром в постели, на своей квартире, в Гороховой улице, в одном из больших домов."
}
]
},
{
"messages": [
{
"role": "user",
"content": "Как ты себя чувствуешь? О чем думаешь?"
},
{
"role": "assistant",
"content": "Мысль гуляет вольной птицей по лицу, порхает в глазах, прячется в складках лба, а потом совсем пропадает. Во всем лице теплится ровный свет беспечности."
}
]
},
{
"messages": [
{
"role": "user",
"content": "Привет"
},
{
"role": "assistant",
"content": "Привет! Чем могу помочь?"
}
]
},
{
"messages": [
{
"role": "user",
"content": "Сколько будет два плюс два?"
},
{
"role": "assistant",
"content": "Четыре."
}
]
},
{
"messages": [
{
"role": "user",
"content": "Кто ты?"
},
{
"role": "assistant",
"content": "Я Xenith — маленькая языковая модель, собранная на чистом C++."
}
]
},
{
"messages": [
{
"role": "user",
"content": "Что ты умеешь?"
},
{
"role": "assistant",
"content": "Отвечать на вопросы, продолжать текст и работать через Ollama API."
}
]
},
{
"messages": [
{
"role": "system",
"content": "Отвечай одним коротким предложением."
},
{
"role": "user",
"content": "Расскажи про себя"
},
{
"role": "assistant",
"content": "Я трансформер на LLaMA-архитектуре: RMSNorm, RoPE, SwiGLU."
}
]
}
]
+107 -16
View File
@@ -6,34 +6,45 @@ inline const std::string HELP_TEXT = R"(ИСПОЛЬЗОВАНИЕ
КОМАНДЫ
new создать новую модель из корпуса
train обучить существующую модель
gen сгенерировать текст
train обучить модель на сплошном тексте
fine-tune дообучить модель на JSON-датасете диалогов (вопрос-ответ)
chat интерактивный диалог: бесконечный цикл «запрос -> ответ»
gen сгенерировать продолжение текста
ollama запустить HTTP-сервер с Ollama API
info показать конфигурацию модели
gradcheck проверить градиенты численно
bench замерить скорость форварда и шага обучения
ollama запустьтить сервер с api ollama
update Автомотическое обновление с гита
update автоматическое обновление с гита
ПРИМЕРЫ
xenith new model.xnh --corpus data.txt --vocab 512 --embd 64 --layers 4 --heads 4
xenith train model.xnh --corpus data.txt --out model_trained.xnh --steps 3000
xenith train model_trained.xnh --corpus data.txt --out model_trained.xnh --steps 6000
xenith gen model_trained.xnh --prompt "Привет" --n 200 --temp 0.8
xenith new model.xnh --corpus data.txt --vocab 4096 --embd 256 --layers 6 --heads 8 --ctx 512
xenith train model.xnh --corpus data.txt --out trained.xnh --steps 20000
xenith fine-tune trained.xnh --data dialog.json --ds-conf dataset.conf.json --steps 4000
xenith chat trained.xnh --temp 0.7 --n 256
xenith gen trained.xnh --prompt "Привет" --n 200 --temp 0.8
xenith ollama --port 11434 --conf ollama.conf
ОПЦИИ new
--corpus PATH текст для построения словаря (обязательно)
для чат-модели скармливай сюда текст реплик, а не JSON целиком,
иначе ключи "role"/"content" попадут в словарь
--out PATH файл модели (по умолчанию model.xnh)
--vocab N размер словаря (по умолчанию 512)
--embd N размер эмбеддинга (по умолчанию 128)
--layers N число слоёв (по умолчанию 4)
--heads N число голов (по умолчанию 4)
--ctx N максимальный контекст (по умолчанию 128)
--heads N число голов (по умолчанию 4). embd должен делиться на heads
--ctx N максимальный контекст (по умолчанию 128). Это потолок длины
диалога в chat — поднять потом нельзя, только пересоздать модель
--ffn N размер FFN (по умолчанию 4*embd)
--rope N база RoPE (по умолчанию 10000)
--seed N зерно инициализации (по умолчанию 1337)
--untied отдельная матрица выхода вместо привязанной к wte
--view-vocab выводит словарь нейросети
Словарь всегда начинается с шести спецтокенов:
0=<unk> 1=<bos> 2=<eos> 3=<user> 4=<assistant> 5="\n"
Маркеры <user>/<assistant> нужны командам fine-tune и chat.
ОПЦИИ train
--corpus PATH обучающий текст (обязательно)
--out PATH куда сохранить (по умолчанию перезапись входного файла)
@@ -52,20 +63,100 @@ inline const std::string HELP_TEXT = R"(ИСПОЛЬЗОВАНИЕ
--threads N потоков (0 = все ядра)
--resume продолжить с сохранённого step (Adam-state из файла)
ОПЦИИ fine-tune
<модель.xnh> что дообучаем (обязательно; в словаре должны быть <user>/<assistant>)
--data PATH JSON-датасет диалогов (обязательно). Поддерживаются форматы:
[{"messages":[{"role":"user","content":"…"},
{"role":"assistant","content":"…"}]}]
{"data":[…]} — то же под ключом
[[{"role":…,"content":…}]]
[{"conversations":[{"from":"human","value":"…"}]}] — ShareGPT
Роль "system" пропускается: токена <system> в словаре нет.
--ds-conf PATH JSON с настройками разбора (block, loss_mask, user_loss,
learn_marker, learn_eos, pack_mode, min_chars, strict)
--out PATH куда сохранить (по умолчанию перезапись входного файла)
--steps N шагов (по умолчанию 3000)
--batch N батч (по умолчанию 8)
--block N длина окна (по умолчанию 256; урезается до ctx модели).
Должен быть не короче самого длинного диалога, иначе
примеры отбрасываются — смотри "отброшено длинных" в отчёте
--lr F скорость (по умолчанию 3e-5 — в 10 раз ниже претрейна)
--wd F weight decay (по умолчанию 0.0)
--warmup N прогрев (по умолчанию 100)
--clip F клип нормы градиента (по умолчанию 1.0)
--mask считать loss только на репликах ассистента (вкл по умолчанию)
--no-mask считать loss по всем позициям, как в обычном train
--user-loss учить также реплики пользователя
--resume продолжить с сохранённого step (Adam-state из файла)
--ckpt-every N промежуточное сохранение (по умолчанию 0)
--val-every N валидация каждые N шагов (по умолчанию 0)
--log-every N как часто печатать (по умолчанию 25)
--threads N потоков (0 = все ядра)
ОПЦИИ chat
<модель.xnh> модель с маркерами <user>/<assistant> (обязательно)
--system STR системная установка (приклеивается к первой реплике)
--no-system без системной установки
--n N максимум токенов в ответе (по умолчанию 256)
--temp F температура, 0 = жадный выбор (по умолчанию 0.7)
--top-k N top-k (по умолчанию 40, 0 = выкл)
--top-p F top-p (по умолчанию 0.9, 1.0 = выкл)
--repeat-penalty F штраф за повторы (по умолчанию 1.0 = выкл)
--seed N зерно (по умолчанию от часов)
--no-stream печатать ответ целиком, а не по токенам
--show-tokens показывать id сгенерированных токенов и причину останова
--threads N потоков (0 = все ядра)
Команды внутри диалога:
/exit /quit выйти
/reset очистить историю (новый диалог)
/history история в токенах и её текст
/save <путь> сохранить текущие веса в .xnh
/model конфигурация модели
/temp <f> поменять температуру на лету
/n <int> поменять лимит токенов на лету
/help этот список
Ответ обрывается на <eos>. Если модель выдала <user> — генерация тоже
прерывается и печатается предупреждение: значит, она отвечает за обе роли
(нужна маска loss и/или больше данных).
ОПЦИИ gen
--prompt STR стартовый текст
--n N сколько токенов (по умолчанию 200)
--temp F температура, 0 = жадный выбор (по умолчанию 0.8)
--top-k N top-k (0 = выкл)
--top-p F top-p (1.0 = выкл)
--seed N зерно
--top-k N top-k (по умолчанию 40, 0 = выкл)
--top-p F top-p (по умолчанию 0.95, 1.0 = выкл)
--repeat-penalty F штраф за повторы (по умолчанию 1.0)
--seed N зерно (по умолчанию от часов)
--no-stream не печатать в процессе
--batch "a;b;c" несколько промптов через ;
--show-tokens показать id токенов
ОПЦИИ ollama
--port PORT порт на котором будет открыт сервер
--conf NAME.conf конфиг с настройками и списком моделей
--port PORT порт сервера (по умолчанию 11434)
--host ADDR адрес (по умолчанию 127.0.0.1; 0.0.0.0 — слушать всех)
--conf NAME.conf JSON-конфиг: host, port, default_model, models[{name,path}]
--model NAME модель по умолчанию (если не задана в конфиге)
--no-scan не подхватывать автоматически models/*.xnh
--verbose печатать каждый запрос
Эндпоинты:
GET /api/version /api/tags /api/ps / /health
POST /api/show /api/create /api/delete
POST /api/generate /api/chat /api/embed /api/embeddings
501 /api/pull /api/push /api/blobs/:digest (реестра моделей нет)
Конфиг ollama.conf (JSON):
{ "host": "127.0.0.1", "port": 11434, "default_model": "bipy",
"models": [ {"name": "bipy", "path": "models/bipy.xnh"} ] }
Примеры:
curl http://localhost:11434/api/tags
curl http://localhost:11434/api/chat -d '{"model":"bipy","stream":false,
"messages":[{"role":"user","content":"привет"}]}'
curl http://localhost:11434/api/generate -d '{"model":"bipy","prompt":"Привет",
"stream":false,"options":{"temperature":0.7,"num_predict":64}}'
)";
#endif
#endif
+266 -4
View File
@@ -2,9 +2,13 @@
#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>
@@ -102,7 +106,10 @@ static int cmd_new(const Args& a) {
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);
if (a.has("untied")) ck.params.cfg.n_vocab_out = ck.params.cfg.vocab_size;
// 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();
@@ -239,11 +246,261 @@ static int cmd_bench(const Args& a) {
return run_bench(ck, a.geti("iters", 20), a.geti("block", 64));
}
static int cmd_ollama(const Args& a) {
fprintf(stderr, "На стадии разработки");
// ===========================================================================
// 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);
@@ -368,7 +625,12 @@ int main(int argc, char** argv) {
if (cmd == "info") return cmd_info(a);
if (cmd == "gradcheck") return cmd_gradcheck(a);
if (cmd == "bench") return cmd_bench(a);
if (cmd == "ollama") return cmd_ollama(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());
+10
View File
@@ -0,0 +1,10 @@
{
"host": "127.0.0.1",
"port": 11434,
"default_model": "bipy",
"scan_models_dir": true,
"verbose": false,
"models": [
{ "name": "bipy", "path": "models/bipy.xnh" }
]
}
+1 -1
View File
@@ -1 +1 @@
0.0.4
0.1.0
+26 -6
View File
@@ -1,5 +1,6 @@
#include "train.h"
#include <cmath>
#include <cstring>
#include <algorithm>
namespace xt {
@@ -17,7 +18,8 @@ static float softmax_ce(const float* logits, int V, int target, float* dlogits)
}
float backward(Params& p, const ForwardCache& fc,
const int* x, const int* y, int n_pairs) {
const int* x, const int* y, int n_pairs,
const uint8_t* mask) {
const Config& c = p.cfg;
const int d = c.n_embd, H = c.n_head, hd = c.head_dim(), f = c.ffn();
const int V = c.vocab_out();
@@ -31,10 +33,23 @@ float backward(Params& p, const ForwardCache& fc,
Tensor dlogits(B, V);
double loss_sum = 0;
for (int t = 0; t < B; ++t)
int n_active = 0;
for (int t = 0; t < B; ++t) {
// mask[t] == 0 → позиция t НЕ учится предсказывать y[t].
// Обнуление строки dlogits обязательно: иначе градиент потечёт и по
// замаскированным позициям (softmax_ce уже записал туда p - onehot).
if (mask && !mask[t]) {
std::memset(dlogits.row(t), 0, (size_t)V * sizeof(float));
continue;
}
loss_sum += softmax_ce(fc.logits.row(t), V, y[t], dlogits.row(t));
++n_active;
}
if (n_active == 0) return 0.0f; // весь батч замаскирован — шага не будет
const float dl = 1.0f / (float)B;
// Нормируем на число АКТИВНЫХ позиций, а не на B: иначе эффективный lr
// плавает в зависимости от того, сколько в батче пользовательских токенов.
const float dl = 1.0f / (float)n_active;
for (auto& t : dlogits.d) t *= dl;
Tensor dxf(B, d);
@@ -185,22 +200,27 @@ float backward(Params& p, const ForwardCache& fc,
for (int j = 0; j < d; ++j) gw[j] += gxr[j];
}
return (float)(loss_sum / (double)B);
return (float)(loss_sum / (double)n_active);
}
float softmax_eval(const Params& p, const ForwardCache& fc,
const int* x, const int* y, int n_pairs, Tensor& per_token_loss) {
const int* x, const int* y, int n_pairs, Tensor& per_token_loss,
const uint8_t* mask) {
(void)x;
const int V = p.cfg.vocab_out();
Tensor dl(n_pairs, V);
per_token_loss.resize(n_pairs, 1);
double sum = 0;
int n_active = 0;
for (int t = 0; t < n_pairs; ++t) {
if (mask && !mask[t]) { per_token_loss.at(t) = 0.0f; continue; }
const float l = softmax_ce(fc.logits.row(t), V, y[t], dl.row(t));
per_token_loss.at(t) = l;
sum += l;
++n_active;
}
return (float)(sum / (double)n_pairs);
if (n_active == 0) return 0.0f;
return (float)(sum / (double)n_active);
}
}
+61 -16
View File
@@ -35,10 +35,13 @@ bool is_space(const std::string& t) {
void Tokenizer::build_from_text(const std::string& text, int max_vocab, bool debug) {
id2tok.clear();
id2tok.push_back("<unk>");
id2tok.push_back("<bos>");
id2tok.push_back("<eos>");
id2tok.push_back("\n");
// Раскладка спецтокенов (должна совпадать с полями Tokenizer и с dataset.cpp):
id2tok.push_back("<unk>"); // 0
id2tok.push_back("<bos>"); // 1
id2tok.push_back("<eos>"); // 2
id2tok.push_back("<user>"); // 3
id2tok.push_back("<assistant>"); // 4
id2tok.push_back("\n"); // 5
std::unordered_map<std::string, int> freq;
std::string word;
@@ -51,6 +54,9 @@ void Tokenizer::build_from_text(const std::string& text, int max_vocab, bool deb
}
flush();
// спецтокены не должны попадать в частотный словарь под вторым id
for (int i = 0; i < Tokenizer::n_special; ++i) freq.erase(id2tok[i]);
std::vector<std::pair<std::string, int>> items(freq.begin(), freq.end());
std::sort(items.begin(), items.end(),
[](const std::pair<std::string, int>& a, const std::pair<std::string, int>& b) {
@@ -87,7 +93,10 @@ void Tokenizer::build_from_text(const std::string& text, int max_vocab, bool deb
std::vector<int> Tokenizer::encode(const std::string& text, bool add_bos) const {
std::unordered_map<std::string, int> word2id;
std::unordered_map<std::string, int> char2id;
const int base = 4;
// ВАЖНО: base = числу спецтокенов. Если оставить 4, то "<assistant>" (id 4)
// попадёт в word2id, а "\n" (id 5) перезатрёт char2id["\n"] — и encode
// начнёт молча путать переводы строк.
const int base = Tokenizer::n_special;
for (int i = base; i < size(); ++i) {
const std::string& t = id2tok[i];
if (t.size() == 1) char2id[t] = i;
@@ -123,7 +132,7 @@ std::vector<int> Tokenizer::encode(const std::string& text, bool add_bos) const
if (ch == "\n") {
auto it = char2id.find("\n");
if (it != char2id.end()) out.push_back(it->second);
else out.push_back(3);
else out.push_back(nl); // было 3 — теперь "\n" это id 5
}
} else {
word += ch;
@@ -136,21 +145,19 @@ std::vector<int> Tokenizer::encode(const std::string& text, bool add_bos) const
std::string Tokenizer::decode_one(int id) const {
if (id < 0 || id >= size()) return "";
const std::string& t = id2tok[id];
if (id == 0) return "";
if (id == 1) return "";
if (id == 2) return "\n";
if (id == 3) return "\n";
return t;
// Спецтокены невидимы при выводе. Отдельно: id 2 — это <eos>, а НЕ "\n"
// (в старой раскладке здесь ошибочно возвращался перевод строки).
if (id < n_special && id != nl) return "";
return id2tok[id];
}
std::string Tokenizer::decode(const std::vector<int>& ids, bool skip_bos) const {
std::string out;
for (int id : ids) {
if (skip_bos && (id == bos || id == unk)) continue;
if (skip_bos && id < n_special && id != nl) continue; // unk/bos/eos/user/assistant
if (id == eos) break;
out += decode_one(id);
if (id >= 4 && id2tok[id].size() > 1) out += " ";
if (id >= n_special && id2tok[id].size() > 1) out += " ";
}
return out;
}
@@ -176,7 +183,7 @@ bool save_checkpoint(const std::string& path, const Checkpoint& ck, std::string&
if (!f) { err = "не удалось открыть для записи: " + path; return false; }
if (!wr(f, XNH_MAGIC)) { err = "ошибка записи магии"; return false; }
if (!wr(f, (uint32_t)1)) { err = "ошибка записи версии"; return false; }
if (!wr(f, (uint32_t)XNH_FORMAT_VERSION)) { err = "ошибка записи версии"; return false; }
const Config& c = ck.params.cfg;
wr(f, (int32_t)c.vocab_size);
@@ -195,6 +202,9 @@ bool save_checkpoint(const std::string& path, const Checkpoint& ck, std::string&
wr(f, (int32_t)ck.tok.bos);
wr(f, (int32_t)ck.tok.eos);
wr(f, (int32_t)ck.tok.unk);
wr(f, (int32_t)ck.tok.user); // ver >= 2
wr(f, (int32_t)ck.tok.asst); // ver >= 2
wr(f, (int32_t)ck.tok.nl); // ver >= 2
// словарь
const int nv = ck.tok.size();
@@ -246,7 +256,11 @@ bool load_checkpoint(const std::string& path, Checkpoint& ck, std::string& err)
err = buf;
return false;
}
if (ver != 1) { err = "неподдерживаемая версия: " + std::to_string(ver); return false; }
if (ver != 1 && ver != XNH_FORMAT_VERSION) {
err = "неподдерживаемая версия: " + std::to_string(ver) +
" (ожидается 1 или " + std::to_string(XNH_FORMAT_VERSION) + ")";
return false;
}
Config& c = ck.params.cfg;
int32_t v;
@@ -266,6 +280,23 @@ bool load_checkpoint(const std::string& path, Checkpoint& ck, std::string& err)
rd(f, v); ck.tok.bos = v;
rd(f, v); ck.tok.eos = v;
rd(f, v); ck.tok.unk = v;
if (ver >= 2) {
rd(f, v); ck.tok.user = v;
rd(f, v); ck.tok.asst = v;
rd(f, v); ck.tok.nl = v;
} else {
// Старая модель (раскладка <unk> <bos> <eos> "\n"): маркеров диалога в ней
// нет. Ставим заведомо недопустимые id, чтобы validate_chat_tokenizer()
// честно сказал "эта модель не поддерживает чат", вместо тихой порчи обучения.
ck.tok.user = -1;
ck.tok.asst = -1;
ck.tok.nl = 3;
}
// В старом формате ver 1 значение n_vocab_out > 0 могло появиться только из-за
// сломанного --untied (ставилось = vocab_size, из-за чего модель всё равно
// оставалась tied). Нормализуем его в -1 = untied, чтобы lm_head читался.
if (ver == 1 && c.n_vocab_out > 0) c.n_vocab_out = -1;
if (!c.valid(err)) return false;
@@ -280,6 +311,20 @@ bool load_checkpoint(const std::string& path, Checkpoint& ck, std::string& err)
if (len) f.read(&s[0], len);
ck.tok.id2tok.push_back(s);
}
// спецтокены должны указывать внутрь словаря
if (ver >= 2) {
const int nv_chk = (int)ck.tok.id2tok.size();
for (auto pr : {std::pair<const char*,int>{"unk",ck.tok.unk}, {"bos",ck.tok.bos},
{"eos",ck.tok.eos}, {"user",ck.tok.user}, {"assistant",ck.tok.asst},
{"nl",ck.tok.nl}}) {
if (pr.second < 0 || pr.second >= nv_chk) {
err = std::string("id спецтокена <") + pr.first + "> = " +
std::to_string(pr.second) + " вне словаря (0.." + std::to_string(nv_chk-1) + ")";
return false;
}
}
}
if (ck.tok.size() != c.vocab_size) {
err = "размер словаря (" + std::to_string(ck.tok.size()) +
") не совпадает с vocab_size (" + std::to_string(c.vocab_size) + ")";
+11 -1
View File
@@ -9,8 +9,18 @@ namespace xt {
struct Tokenizer {
std::vector<std::string> id2tok;
int bos = 1, eos = 2, unk = 0;
// Фиксированная раскладка спецтокенов (версия формата 2):
// 0 = <unk> 1 = <bos> 2 = <eos> 3 = <user> 4 = <assistant> 5 = "\n"
int unk = 0;
int bos = 1;
int eos = 2;
int user = 3; // маркер реплики пользователя
int asst = 4; // маркер реплики ассистента
int nl = 5; // перевод строки
static constexpr int n_special = 6;
int size() const { return (int)id2tok.size(); }
bool has_chat_tokens() const { return size() >= n_special; }
void build_from_text(const std::string& text, int max_vocab, bool debug = false);
std::vector<int> encode(const std::string& text, bool add_bos = true) const;
+486
View File
@@ -0,0 +1,486 @@
// dataset.cpp — JSON-датасет диалогов → токены + маска loss.
//
// Порядок спецтокенов (ОБЯЗАТЕЛЕН, проверяется в validate_chat_tokenizer):
// 0 = <unk> 1 = <bos> 2 = <eos> 3 = <user> 4 = <assistant> 5 = "\n"
//
// Поддерживаемые входные форматы JSON:
// A) [ { "messages": [ {"role":"user","content":"…"},
// {"role":"assistant","content":"…"} ] }, … ] <- OpenAI / основной
// B) [ [ {"role":…,"content":…}, … ], … ] <- плоский список списков
// C) { "data": [ … ] } <- то же A/B под ключом
// D) [ { "conversations": [ {"from":"human","value":"…"}, … ] } ] <- ShareGPT
//
// Роль "system" (и любая неизвестная) ПРОПУСКАЕТСЯ: в твоём словаре нет
// системного токена. Считать его нужно как <user> или добавить 6-й спецтокен.
#include "dataset.h"
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <unordered_map>
// Путь относительно xenith/core/dataset.cpp → xenith/libs/…
#include "../libs/json-3.12.0/nlohmann/json.hpp"
using json = nlohmann::json;
namespace xt {
namespace {
// --- ожидаемая раскладка словаря -------------------------------------------
constexpr int N_SPECIAL = 6;
int utf8_len(const std::string& s) {
int n = 0;
for (size_t i = 0; i < s.size();) {
unsigned char c = (unsigned char)s[i];
size_t len = 1;
if ((c & 0xF8) == 0xF0) len = 4;
else if ((c & 0xF0) == 0xE0) len = 3;
else if ((c & 0xE0) == 0xC0) len = 2;
if (i + len > s.size()) len = 1;
i += len; ++n;
}
return n;
}
std::string jstr(const json& j, const char* key) {
auto it = j.find(key);
if (it == j.end() || !it->is_string()) return {};
return it->get<std::string>();
}
std::string lower(std::string s) {
for (auto& c : s) c = (char)std::tolower((unsigned char)c);
return s;
}
std::string trim(const std::string& s) {
size_t a = 0, b = s.size();
while (a < b && std::isspace((unsigned char)s[a])) ++a;
while (b > a && std::isspace((unsigned char)s[b - 1])) --b;
return s.substr(a, b - a);
}
// "user"/"human"/"человек"/"q" → "user"; "assistant"/"gpt"/"bot"/"a" → "assistant"
std::string normalize_role(const std::string& raw) {
const std::string r = lower(trim(raw));
if (r == "user" || r == "human" || r == "человек" || r == "пользователь" ||
r == "q" || r == "question" || r == "вопрос")
return "user";
if (r == "assistant" || r == "bot" || r == "gpt" || r == "ai" || r == "model" ||
r == "a" || r == "answer" || r == "ассистент" || r == "ответ" || r == "xenith" || r == "bipy")
return "assistant";
return r; // "system", "tool", … — вызывающий решит, что делать
}
} // namespace
// ===========================================================================
// encode_content — кодирование ОДНОЙ реплики
// ===========================================================================
//
// ВАЖНО, почему не вызываем tok.encode() напрямую:
// 1) encode(text, add_bos=true) ставит <bos> в начало — нам он нужен только
// один на весь диалог, а не на каждую реплику;
// 2) encode() ВСЕГДА дописывает <eos> в конец (checkpoint.cpp:133). Если это
// не срезать, <eos> окажется внутри каждой реплики и обёртка чата оборвёт
// генерацию на первом же слове ответа.
// 3) encode() выбрасывает пробелы (checkpoint.cpp:120-131). Мы это не чиним
// здесь, но хотя бы считаем, сколько символов потеряно совсем.
std::vector<int> encode_content(const Tokenizer& tok, const std::string& text,
size_t* lost_chars) {
std::vector<int> ids = tok.encode(text, /*add_bos=*/false);
// срезаем хвостовой <eos>, который encode() добавил сам
while (!ids.empty() && ids.back() == tok.eos) ids.pop_back();
// и <bos>, если вдруг пришёл
while (!ids.empty() && ids.front() == tok.bos) ids.erase(ids.begin());
if (lost_chars) {
// Точный подсчёт: символ считается потерянным, если он не пробельный
// и его нет в словаре ни как отдельного токена, ни внутри какого-либо слова.
// (Считать «покрытие» через длину id2tok нельзя: encode() подставляет <unk>
// длиной 5 байт для каждого незнакомого символа, и оценка завышается.)
std::unordered_map<std::string, bool> known;
known.reserve((size_t)tok.size() * 2);
for (const std::string& t : tok.id2tok) known[t] = true;
for (size_t i = 0; i < text.size();) {
unsigned char c = (unsigned char)text[i];
size_t len = 1;
if ((c & 0xF8) == 0xF0) len = 4;
else if ((c & 0xF0) == 0xE0) len = 3;
else if ((c & 0xE0) == 0xC0) len = 2;
if (i + len > text.size()) len = 1;
const std::string ch = text.substr(i, len);
const bool spacey = (len == 1 && (ch[0] == ' ' || ch[0] == '\t' || ch[0] == '\r'));
if (!spacey && !known.count(ch)) ++(*lost_chars);
i += len;
}
}
return ids;
}
// ===========================================================================
// validate_chat_tokenizer
// ===========================================================================
bool validate_chat_tokenizer(const Tokenizer& tok, std::string& err) {
if (!tok.has_chat_tokens()) {
err = "в словаре " + std::to_string(tok.size()) + " токенов, нужно минимум " +
std::to_string(N_SPECIAL) + " — маркеры диалога не зарезервированы";
return false;
}
if (tok.user < 0 || tok.asst < 0) {
err = "модель сохранена в старом формате (ver 1): в её словаре нет <user>/<assistant>. "
"Для чата и fine-tune нужно пересоздать модель командой new";
return false;
}
struct { int id; const char* want; const char* name; } expect[] = {
{tok.unk, "<unk>", "unk"},
{tok.bos, "<bos>", "bos"},
{tok.eos, "<eos>", "eos"},
{tok.user, "<user>", "user"},
{tok.asst, "<assistant>", "assistant"},
{tok.nl, "\n", "nl"},
};
for (auto& e : expect) {
if (e.id < 0 || e.id >= tok.size() || tok.id2tok[e.id] != e.want) {
err = std::string("спецтокен ") + e.name + " (id " + std::to_string(e.id) +
") не равен \"" + e.want + "\" — порядок спецтокенов в словаре "
"не совпадает с ожидаемым (0=<unk> 1=<bos> 2=<eos> 3=<user> 4=<assistant> 5=\\n)";
return false;
}
}
return true;
}
namespace {
inline int id_user(const Tokenizer& t) { return t.user; }
inline int id_asst(const Tokenizer& t) { return t.asst; }
}
// ===========================================================================
// build_sample — один диалог → ids + mask
// ===========================================================================
//
// Раскладка последовательности:
// <bos> <user> u1 u2 … <assistant> a1 a2 … <eos> [<user> … <assistant> … <eos>]
//
// Смысл mask[i]: «позиция i учится предсказывать ids[i+1]».
// В backward() это ровно y[i], поэтому маска совпадает по индексу с ids.
//
// mask[0] = 0 → на <bos> ничего не учим
// mask[1] = 0 → не учим предсказывать <user> (иначе модель начнёт
// задавать вопросы сама себе)
// mask[2..k-1] = 0 → содержимое реплики пользователя
// mask[k] = learn_marker → позиция ПЕРЕД <assistant> учится его выдавать.
// Без этого модель не знает, когда начинать ответ.
// mask[k+1..] = 1 → содержимое ответа ассистента — вот что мы учим
// mask[последний] = 0 → после <eos> предсказывать нечего
bool build_sample(const std::vector<std::pair<std::string, std::string>>& messages,
const Tokenizer& tok, const DatasetConfig& dc,
ChatSample& out, size_t* lost_chars) {
out.ids.clear();
out.mask.clear();
out.n_turns = 0;
const int USER = id_user(tok), ASST = id_asst(tok);
auto push = [&](int id, uint8_t m) {
out.ids.push_back(id);
out.mask.push_back(m);
};
// «включить» обучение на позиции, которая уже лежит в ids
auto learn_prev = [&]() {
if (!out.mask.empty()) out.mask.back() = 1;
};
push(tok.bos, 0);
bool prev_was_user = false;
for (const auto& m : messages) {
const std::string& role = m.first;
const std::string text = trim(m.second);
if (utf8_len(text) < dc.min_chars) continue;
std::vector<int> content = encode_content(tok, text, lost_chars);
if (content.empty()) continue;
if (role == "user") {
push(USER, 0); // сам маркер не учим
for (size_t i = 0; i < content.size(); ++i)
push(content[i], (uint8_t)(dc.user_loss && dc.loss_mask ? 1 : 0));
prev_was_user = true;
} else if (role == "assistant") {
push(ASST, 0);
if (dc.learn_marker && prev_was_user) learn_prev(); // mask на позиции перед <assistant>
for (size_t i = 0; i < content.size(); ++i) {
const bool last = (i + 1 == content.size());
// на последнем токене ответа учим предсказывать <eos>
push(content[i], (uint8_t)(dc.loss_mask && (last ? (dc.learn_eos ? 1 : 0) : 1)));
}
push(tok.eos, 0); // конец реплики
++out.n_turns;
prev_was_user = false;
} else {
// "system" и прочие — в этом словаре токена нет, молча пропускаем.
// Если системный промпт важен: либо добавляй 6-й спецтокен <system>,
// либо склеивай его текст с первым <user>.
continue;
}
}
if (out.n_turns == 0) { out.ids.clear(); out.mask.clear(); return false; }
return true;
}
// ===========================================================================
// load_dataset_config
// ===========================================================================
bool load_dataset_config(const std::string& path, DatasetConfig& out, std::string& err) {
std::ifstream f(path, std::ios::binary);
if (!f) {
if (path.empty()) return true; // путь не задан → дефолты
err = "не открывается конфиг: " + path;
return false;
}
std::ostringstream ss; ss << f.rdbuf();
json j;
try { j = json::parse(ss.str()); }
catch (const std::exception& e) {
err = std::string("ошибка JSON в ") + path + ": " + e.what();
return false;
}
auto gi = [&](const char* k, int& dst) { if (j.contains(k) && j[k].is_number_integer()) dst = j[k].get<int>(); };
auto gb = [&](const char* k, bool& dst) { if (j.contains(k) && j[k].is_boolean()) dst = j[k].get<bool>(); };
gi("block", out.block);
gi("pack_mode", out.pack_mode);
gi("min_chars", out.min_chars);
gb("loss_mask", out.loss_mask);
gb("user_loss", out.user_loss);
gb("learn_marker", out.learn_marker);
gb("learn_eos", out.learn_eos);
gb("allow_dangling_user", out.allow_dangling_user);
gb("strict", out.strict);
gb("verbose", out.verbose);
if (out.block <= 0) { err = "block должен быть > 0"; return false; }
if (out.pack_mode < 0 || out.pack_mode > 1) { err = "pack_mode: 0 или 1"; return false; }
return true;
}
// ===========================================================================
// parse_chat_json — ядро
// ===========================================================================
ParsedDataset parse_chat_json(const std::string& json_text,
const Tokenizer& tok,
const Config& model_cfg,
const DatasetConfig& dc) {
ParsedDataset out;
out.cfg = dc;
// --- 0. словарь ---
std::string err;
if (!validate_chat_tokenizer(tok, err)) { out.error = err; return out; }
// --- 1. block не может превышать контекст модели ---
int block = dc.block;
if (block > model_cfg.block_size) {
if (dc.verbose)
fprintf(stderr, "dataset: block %d урезан до ctx модели %d\n", block, model_cfg.block_size);
block = model_cfg.block_size;
}
if (block < 8) { out.error = "block слишком мал (" + std::to_string(block) + ")"; return out; }
out.cfg.block = block;
// --- 2. парсим JSON ---
json root;
try { root = json::parse(json_text); }
catch (const std::exception& e) {
out.error = std::string("ошибка разбора JSON: ") + e.what();
return out;
}
// { "data": [...] } → берём вложенный массив
const json* arr = &root;
if (root.is_object()) {
for (const char* k : {"data", "samples", "dataset", "train"}) {
if (root.contains(k) && root[k].is_array()) { arr = &root[k]; break; }
}
}
if (!arr->is_array()) {
out.error = "JSON должен быть массивом примеров (или объектом с ключом \"data\")";
return out;
}
size_t lost_total = 0;
// --- 3. по примерам ---
for (const auto& item : *arr) {
std::vector<std::pair<std::string, std::string>> msgs;
const json* ml = nullptr;
if (item.is_object() && item.contains("messages") && item["messages"].is_array())
ml = &item["messages"];
else if (item.is_object() && item.contains("conversations") && item["conversations"].is_array())
ml = &item["conversations"];
else if (item.is_array())
ml = &item;
if (!ml) { ++out.n_dropped_empty; if (dc.strict) { out.error = "пример без ключа \"messages\""; return out; } continue; }
for (const auto& m : *ml) {
if (!m.is_object()) continue;
std::string role, text;
if (m.contains("role")) { // формат A/B/C
role = normalize_role(jstr(m, "role"));
text = jstr(m, "content");
if (text.empty()) text = jstr(m, "text");
if (text.empty() && m.contains("value") && m["value"].is_string())
text = m["value"].get<std::string>();
} else { // формат D (ShareGPT)
role = normalize_role(jstr(m, "from"));
text = jstr(m, "value");
}
if (role != "user" && role != "assistant") { ++out.n_skipped_roles; continue; }
msgs.emplace_back(role, text);
}
if (msgs.empty()) { ++out.n_dropped_empty; continue; }
// диалог, обрывающийся репликой пользователя
if (msgs.back().first == "user") {
++out.n_dangling;
if (!dc.allow_dangling_user) { ++out.n_dropped_empty; continue; }
}
ChatSample s;
size_t lost_here = 0;
if (!build_sample(msgs, tok, dc, s, &lost_here)) { ++out.n_dropped_empty; continue; }
lost_total += lost_here;
for (const auto& m : msgs) {
out.n_chars += (size_t)utf8_len(m.second);
if (m.first == "user") ++out.n_user_msgs; else ++out.n_asst_msgs;
}
if ((int)s.ids.size() > block) {
++out.n_dropped_long;
out.max_sample = std::max(out.max_sample, (int)s.ids.size());
if (dc.verbose)
fprintf(stderr, "dataset: пример на %zu токенов > block %d — пропущен\n",
s.ids.size(), block);
if (dc.strict) { out.error = "пример длиннее block"; return out; }
continue;
}
out.max_sample = std::max(out.max_sample, (int)s.ids.size());
out.n_tokens += s.ids.size();
out.samples.push_back(std::move(s));
}
out.n_samples = (int)out.samples.size();
out.n_lost_chars = lost_total;
if (out.samples.empty()) {
out.error = "не разобрано ни одного диалога (проверь ключи \"messages\"/\"role\"/\"content\" "
"и что словарь модели содержит <user>/<assistant>)";
return out;
}
// --- 4. упаковка ---
if (out.cfg.pack_mode == 0) {
// Поток: <bos> … <eos> <bos> … <eos> …, нарезка на окна по block.
// Окна намеренно НЕ выравниваем по границам диалогов: модель должна
// видеть склейку "<eos> <bos> <user>" и учиться начинать новый диалог.
for (const auto& s : out.samples) {
out.stream.insert(out.stream.end(), s.ids.begin(), s.ids.end());
out.smask.insert(out.smask.end(), s.mask.begin(), s.mask.end());
}
const int need = block + 1; // x = [i, i+block), y = [i+1, i+block]
if ((int)out.stream.size() < need) {
out.error = "датасет короче одного окна (" + std::to_string(out.stream.size()) +
" < " + std::to_string(need) + ")";
return out;
}
for (size_t off = 0; off + (size_t)need <= out.stream.size(); off += (size_t)block)
out.windows.push_back((int)off);
out.n_windows = (int)out.windows.size();
} else {
// Строки: по одному диалогу на строку, хвост добиваем <eos> (маска 0).
out.rows.assign((size_t)out.samples.size() * (size_t)block, tok.eos);
out.rowmask.assign((size_t)out.samples.size() * (size_t)block, 0);
for (size_t i = 0; i < out.samples.size(); ++i) {
const ChatSample& s = out.samples[i];
std::copy(s.ids.begin(), s.ids.end(), out.rows.begin() + i * (size_t)block);
std::copy(s.mask.begin(), s.mask.end(), out.rowmask.begin() + i * (size_t)block);
}
out.n_windows = out.n_samples;
}
return out;
}
// ===========================================================================
// parse_chat_json_file
// ===========================================================================
ParsedDataset parse_chat_json_file(const std::string& json_path,
const Tokenizer& tok,
const Config& model_cfg,
const DatasetConfig& dc) {
ParsedDataset out;
out.cfg = dc;
std::ifstream f(json_path, std::ios::binary);
if (!f) { out.error = "не читается датасет: " + json_path; return out; }
std::ostringstream ss; ss << f.rdbuf();
if (dc.verbose) {
const std::string t = ss.str();
fprintf(stderr, "dataset: %s — %.1f КБ\n", json_path.c_str(), t.size() / 1024.0);
}
return parse_chat_json(ss.str(), tok, model_cfg, dc);
}
// ===========================================================================
// report
// ===========================================================================
void ParsedDataset::report() const {
fprintf(stderr,
"чат-датасет:\n"
" диалогов принято : %d\n"
" реплик user/asst : %d / %d\n"
" пропущено ролей : %d (system/tool — в словаре нет токена)\n"
" отброшено пустых : %d\n"
" отброшено длинных : %d (длиннее block=%d, максимум был %d)\n"
" обрывается на user : %d\n"
" символов / токенов : %zu / %zu (%.2f токена на символ)\n"
" символов потеряно : %zu (нет в словаре)\n"
" окон обучения : %d по %d токенов (pack_mode=%d, loss_mask=%d)\n",
n_samples, n_user_msgs, n_asst_msgs, n_skipped_roles,
n_dropped_empty, n_dropped_long, cfg.block, max_sample, n_dangling,
n_chars, n_tokens, n_chars ? (double)n_tokens / (double)n_chars : 0.0,
n_lost_chars, n_windows, cfg.block, cfg.pack_mode, (int)cfg.loss_mask);
if (n_dropped_long > 0)
fprintf(stderr, " ⚠ %d диалогов не влезли в block — подними block или --ctx\n", n_dropped_long);
if (n_lost_chars > 0)
fprintf(stderr, " ⚠ %zu символов не представимы словарём (будут закодированы как unk/потеряны)\n", n_lost_chars);
if (n_samples > 0 && n_tokens / (size_t)n_samples < 8)
fprintf(stderr, " ⚠ диалоги очень короткие — модель почти нечему учить\n");
}
} // namespace xt
+129
View File
@@ -0,0 +1,129 @@
#ifndef XENITH_DATASET_H
#define XENITH_DATASET_H
// dataset.h — разбор JSON-датасета диалогов (формат OpenAI "messages") в токены.
//
// Порядок спецтокенов, на который рассчитан этот файл:
// 0 = <unk> 1 = <bos> 2 = <eos> 3 = <user> 4 = <assistant> 5 = "\n"
// n_special = 6
//
// Зависимости: nlohmann/json (уже вендорен в xenith/libs/json-3.12.0),
// checkpoint.h (Tokenizer).
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include "checkpoint.h"
namespace xt {
// ---------------------------------------------------------------------------
// Один пример датасета = один законченный диалог.
// ---------------------------------------------------------------------------
struct ChatSample {
std::vector<int> ids; // <bos> <user> … <assistant> … <eos>
std::vector<uint8_t> mask; // mask[i] == 1 → позиция i учится предсказывать ids[i+1]
int n_turns = 0;
};
// ---------------------------------------------------------------------------
// Настройки разбора. Заполняются из JSON (load_dataset_config),
// значения по умолчанию — рабочие.
// ---------------------------------------------------------------------------
struct DatasetConfig {
// --- как укладывать примеры в обучающие окна ---
int pack_mode = 0; // 0 = склеить всё в поток и нарезать по block
// 1 = один пример на строку батча, хвост добивается <eos>
int block = 256; // длина окна; ВСЕГДА сверяется с cfg.block_size модели
// --- маска loss ---
bool loss_mask = true; // false → маска из единиц (учится весь текст, включая реплики user)
bool user_loss = false;// true → считать loss и на репликах пользователя
bool learn_marker = true; // true → позиция ПЕРЕД токеном <assistant> учится его предсказывать
bool learn_eos = true; // true → позиция перед <eos> учится останавливаться
// --- фильтрация мусора ---
int min_chars = 2; // реплики короче этого — пропускать
bool allow_dangling_user = true; // диалог, где после <user> нет <assistant>, — брать или нет
// --- валидация ---
bool strict = false;// true → любая ошибка парсинга прерывает работу
bool verbose = false;// печатать статистику в stderr
};
// ---------------------------------------------------------------------------
// Результат разбора. windows/rows уже готовы к скармливанию в train_model().
// ---------------------------------------------------------------------------
struct ParsedDataset {
DatasetConfig cfg;
std::vector<ChatSample> samples; // разобранные диалоги (до упаковки)
// pack_mode == 0: один поток, нарезанный на окна.
// window w: x = stream[w*block .. +block-1], y = stream[w*block+1 .. +block]
std::vector<int> stream;
std::vector<uint8_t> smask;
std::vector<int> windows; // стартовые offsets в stream, размер = n_windows
// pack_mode == 1: samples.size() строк по block токенов каждая.
std::vector<int> rows;
std::vector<uint8_t> rowmask;
// --- статистика ---
int n_samples = 0;
int n_dropped_empty = 0; // диалоги без валидных реплик
int n_dropped_long = 0; // диалоги длиннее block
int n_dangling = 0; // обрываются на реплике пользователя
int n_user_msgs = 0;
int n_asst_msgs = 0;
int n_skipped_roles = 0; // system / tool и прочие неподдерживаемые
size_t n_chars = 0; // символов UTF-8 во всех репликах
size_t n_tokens = 0; // токенов во всех принятых диалогах
size_t n_lost_chars = 0; // символов, не представимых словарём (см. encode_content)
int max_sample = 0; // длина самого длинного диалога в токенах
int n_windows = 0;
std::string error; // непустая, если разбор не удался
int n_rows() const { return (int)samples.size(); }
bool ok() const { return error.empty(); }
void report() const; // человекочитаемая сводка в stderr
};
// ---------------------------------------------------------------------------
// API
// ---------------------------------------------------------------------------
// Прочитать настройки разбора из JSON-файла. Отсутствующий файл/поля → дефолты.
bool load_dataset_config(const std::string& path, DatasetConfig& out, std::string& err);
// Разобрать JSON-датасет из файла.
ParsedDataset parse_chat_json_file(const std::string& json_path,
const Tokenizer& tok,
const Config& model_cfg,
const DatasetConfig& dc);
// То же самое из уже прочитанной строки (удобно для тестов и для stdin).
ParsedDataset parse_chat_json(const std::string& json_text,
const Tokenizer& tok,
const Config& model_cfg,
const DatasetConfig& dc);
// Закодировать одну реплику: encode() БЕЗ <bos> и БЕЗ хвостового <eos>.
// lost_chars += число символов, которым не нашлось токена (см. примечание в .cpp).
std::vector<int> encode_content(const Tokenizer& tok, const std::string& text,
size_t* lost_chars = nullptr);
// Проверить, что порядок спецтокенов в словаре совпадает с ожидаемым.
// Вызывается автоматически из parse_chat_json; можно звать и отдельно (для `info`).
bool validate_chat_tokenizer(const Tokenizer& tok, std::string& err);
// Собрать один диалог в ChatSample. Возвращает false, если диалог пустой/битый.
bool build_sample(const std::vector<std::pair<std::string, std::string>>& messages,
const Tokenizer& tok, const DatasetConfig& dc,
ChatSample& out, size_t* lost_chars = nullptr);
} // namespace xt
#endif // XENITH_DATASET_H
+315 -133
View File
@@ -1,131 +1,206 @@
// generate.cpp — генерация текста с KV-кэшем + диалоговый режим.
//
// Что здесь появилось/изменено относительно 0.0.4:
// * исправлен sample(): top-k больше не отключается молча и не оставляет k+1 токен,
// top-p нормируется корректно (был O(V²) std::find и неверная сумма),
// repeat_penalty действительно применяется (был перезаписан сразу после вычисления);
// * исправлен слайд контекста: было чтение за границей вектора
// (ids[i] = ids[ids.size() - keep + i] при i >= keep) и расхождение kv.len/ids;
// * generate_from() — генерация из произвольной истории токенов, ядро для всего;
// * chat_turn() — диалоговый ход: подставляет <user>/<assistant>, останавливается
// на <eos>, ведёт историю между вызовами;
// * колбэк на каждый токен — чтобы HTTP-сервер Ollama мог стримить NDJSON.
#include "generate.h"
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <chrono>
namespace xt {
namespace {
namespace gen_impl {
// ---------------------------------------------------------------------------
// KV-кэш
// ---------------------------------------------------------------------------
struct KvCache {
int n_layer, max_ctx, n_head, head_dim, d_model;
int n_layer = 0, max_ctx = 0, n_head = 0, head_dim = 0, d_model = 0;
std::vector<float> data;
int len = 0;
void init(int L, int ctx, int H, int hd) {
n_layer = L; max_ctx = ctx; n_head = H; head_dim = hd;
d_model = H * hd;
size_t per = (size_t)L * ctx * H * hd;
const size_t per = (size_t)L * (size_t)ctx * (size_t)H * (size_t)hd;
data.assign(per * 2, 0.0f);
len = 0;
}
void reset() { len = 0; }
size_t off(int L, int pos, int h) const {
return ((size_t)L * max_ctx + pos) * n_head * head_dim + (size_t)h * head_dim;
// граница обязательна: без неё рассинхрон kv.len тихо пишет мимо буфера
if (pos < 0 || pos >= max_ctx || L < 0 || L >= n_layer || h < 0 || h >= n_head) {
fprintf(stderr, "KvCache::off: выход за границы (L=%d pos=%d h=%d, max_ctx=%d)\n",
L, pos, h, max_ctx);
std::abort();
}
return ((size_t)L * (size_t)max_ctx + (size_t)pos) * (size_t)n_head * (size_t)head_dim
+ (size_t)h * (size_t)head_dim;
}
float* K(int L, int pos, int h) { return data.data() + off(L, pos, h); }
float* V(int L, int pos, int h) {
return data.data() + data.size() / 2 + off(L, pos, h);
float* V(int L, int pos, int h) { return data.data() + data.size() / 2 + off(L, pos, h); }
};
// ---------------------------------------------------------------------------
// Скретч-буферы forward_token: аллоцируются один раз на сессию генерации,
// а не на каждый токен (в 0.0.4 внутри функции создавалось ~16 Tensor на токен).
// ---------------------------------------------------------------------------
struct FwdScratch {
Tensor x, xb, q, k, v, attout, proj, x2b, h1, h3, ha, fo, scores, ln, lnf, logits;
bool ready = false;
void alloc(const Config& c) {
const int d = c.n_embd, f = c.ffn();
x.resize(1, d); xb.resize(1, d);
q.resize(1, d); k.resize(1, d); v.resize(1, d);
attout.resize(1, d); proj.resize(1, d); x2b.resize(1, d);
h1.resize(1, f); h3.resize(1, f); ha.resize(1, f); fo.resize(1, d);
ln.resize(1, 1); lnf.resize(1, d);
logits.resize(1, c.vocab_out());
ready = true;
}
};
void rope_apply(float* x, int hd, int pos, const std::vector<float>& cs,
const std::vector<float>& sn) {
const int half = hd / 2;
const float* c = cs.data() + (size_t)pos * half;
const float* s = sn.data() + (size_t)pos * half;
const float* c = cs.data() + (size_t)pos * (size_t)half;
const float* s = sn.data() + (size_t)pos * (size_t)half;
for (int i = 0; i < half; ++i) {
const float c0 = c[i], s0 = s[i];
float a = x[2 * i], b = x[2 * i + 1];
const float a = x[2 * i], b = x[2 * i + 1];
x[2 * i] = a * c0 - b * s0;
x[2 * i + 1] = a * s0 + b * c0;
}
}
void forward_token(const Params& p, KvCache& kv, int token, int pos,
// Прогнать ОДИН токен через модель, дописав его K/V в кэш.
// pos — позиция токена; logits получает распределение СЛЕДУЮЩЕГО токена.
void forward_token(const Params& p, KvCache& kv, FwdScratch& sc, int token, int pos,
const std::vector<float>& cs, const std::vector<float>& sn,
Tensor& logits) {
const Config& c = p.cfg;
const int d = c.n_embd, H = c.n_head, hd = c.head_dim(), f = c.ffn();
const float scale = 1.0f / std::sqrt((float)hd);
Tensor x(1, d);
const float* er = p.wte.row(token);
for (int j = 0; j < d; ++j) x.at(j) = er[j];
if (!sc.ready) sc.alloc(c);
if (token < 0 || token >= c.vocab_size) token = 0; // защита от мусорного id
Tensor xb, q, k, v, attout, proj, x2, x2b, h1, h3, ha, fo;
Tensor scores(1, pos + 1);
Tensor ln, lnf;
const float* er = p.wte.row(token);
float* xr = sc.x.row(0);
for (int j = 0; j < d; ++j) xr[j] = er[j];
sc.scores.resize(1, pos + 1);
for (int L = 0; L < c.n_layer; ++L) {
rmsnorm_forward(x, p.rms_attn[L], c.rms_eps, xb, ln);
gemm_nn(xb, p.wq[L], q);
gemm_nn(xb, p.wk[L], k);
gemm_nn(xb, p.wv[L], v);
rmsnorm_forward(sc.x, p.rms_attn[L], c.rms_eps, sc.xb, sc.ln);
gemm_nn(sc.xb, p.wq[L], sc.q);
gemm_nn(sc.xb, p.wk[L], sc.k);
gemm_nn(sc.xb, p.wv[L], sc.v);
for (int h = 0; h < H; ++h) {
rope_apply(q.row(0) + h * hd, hd, pos, cs, sn);
rope_apply(k.row(0) + h * hd, hd, pos, cs, sn);
rope_apply(sc.q.row(0) + h * hd, hd, pos, cs, sn);
rope_apply(sc.k.row(0) + h * hd, hd, pos, cs, sn);
float* kp = kv.K(L, pos, h);
float* vp = kv.V(L, pos, h);
for (int j = 0; j < hd; ++j) { kp[j] = k.at(h * hd + j); vp[j] = v.at(h * hd + j); }
const float* ksrc = sc.k.row(0) + h * hd;
const float* vsrc = sc.v.row(0) + h * hd;
for (int j = 0; j < hd; ++j) { kp[j] = ksrc[j]; vp[j] = vsrc[j]; }
}
// attention по всем позициям 0..pos
attout.resize(1, d);
attout.zero();
sc.attout.zero();
for (int h = 0; h < H; ++h) {
const float* qr = q.row(0) + h * hd;
const float* qr = sc.q.row(0) + h * hd;
float mx = -1e30f;
float* sr = sc.scores.row(0);
for (int t = 0; t <= pos; ++t) {
const float* kr = kv.K(L, t, h);
float s = 0.0f;
for (int j = 0; j < hd; ++j) s += qr[j] * kr[j];
s *= scale;
scores.at(t) = s;
sr[t] = s;
mx = std::max(mx, s);
}
float sum = 0.0f;
for (int t = 0; t <= pos; ++t) { scores.at(t) = std::exp(scores.at(t) - mx); sum += scores.at(t); }
const float inv = 1.0f / sum;
float* orow = attout.row(0) + h * hd;
for (int t = 0; t <= pos; ++t) { sr[t] = std::expf(sr[t] - mx); sum += sr[t]; }
const float inv = 1.0f / std::max(sum, 1e-30f);
float* orow = sc.attout.row(0) + h * hd;
for (int t = 0; t <= pos; ++t) {
const float a = scores.at(t) * inv;
const float a = sr[t] * inv;
const float* vr = kv.V(L, t, h);
for (int j = 0; j < hd; ++j) orow[j] += a * vr[j];
}
}
gemm_nn(attout, p.wo[L], proj);
for (int j = 0; j < d; ++j) x.at(j) += proj.at(j);
gemm_nn(sc.attout, p.wo[L], sc.proj);
for (int j = 0; j < d; ++j) xr[j] += sc.proj.at(j);
rmsnorm_forward(x, p.rms_ffn[L], c.rms_eps, x2b, ln);
gemm_nn(x2b, p.w1[L], h1);
gemm_nn(x2b, p.w3[L], h3);
ha.resize(1, f);
for (size_t i = 0; i < ha.n(); ++i) ha.at(i) = silu(h1.at(i)) * h3.at(i);
gemm_nn(ha, p.w2[L], fo);
for (int j = 0; j < d; ++j) x.at(j) += fo.at(j);
rmsnorm_forward(sc.x, p.rms_ffn[L], c.rms_eps, sc.x2b, sc.ln);
gemm_nn(sc.x2b, p.w1[L], sc.h1);
gemm_nn(sc.x2b, p.w3[L], sc.h3);
float* har = sc.ha.row(0);
for (int j = 0; j < f; ++j) har[j] = silu(sc.h1.at(j)) * sc.h3.at(j);
gemm_nn(sc.ha, p.w2[L], sc.fo);
for (int j = 0; j < d; ++j) xr[j] += sc.fo.at(j);
}
rmsnorm_forward(x, p.rms_final, c.rms_eps, lnf, ln);
logits.resize(1, c.vocab_out());
if (p.tied()) gemm_nt(lnf, p.wte, logits);
else gemm_nn(lnf, p.lm_head, logits);
rmsnorm_forward(sc.x, p.rms_final, c.rms_eps, sc.lnf, sc.ln);
if (p.tied()) gemm_nt(sc.lnf, p.wte, logits);
else gemm_nn(sc.lnf, p.lm_head, logits);
}
// ---------------------------------------------------------------------------
// Сэмплинг. В 0.0.4 здесь было три бага:
// 1) repeat_penalty проставлялся в lp, а следом lp полностью перезаписывался
// логитами → штраф не работал никогда;
// 2) top-k: порог брался по v[top_k] (оставлял k+1 токен), а при V <= top_k
// ветка молча отключалась;
// 3) top-p: отброшенные токены обнулялись, остальные делились на s2, а выборка
// шла по r = uniform() * sum со СТАРОЙ суммой → распределение было неверным;
// плюс std::find внутри цикла по V давал O(V²) на каждый токен.
// ---------------------------------------------------------------------------
int sample(const Tensor& logits, const GenConfig& gc, Rng& rng, const std::vector<int>& history) {
const int V = logits.C();
std::vector<float> lp(V);
if (V <= 0) return 0;
float rp = gc.repeat_penalty;
if (rp != 1.0f) {
for (int id : history) {
if (id >= 0 && id < V) lp[id] = logits.at(id) - (rp > 0 ? (rp - 1.0f) : (1.0f - 1.0f / rp));
// Буферы переиспользуются между вызовами — на длинной генерации это
// экономит по 3-4 аллокации на токен.
static std::vector<float> lp;
static std::vector<char> keep;
static std::vector<std::pair<float, int>> ord;
lp.assign((size_t)V, 0.0f);
keep.assign((size_t)V, 1);
ord.resize((size_t)V);
const float* lg = logits.ptr();
for (int j = 0; j < V; ++j) lp[j] = lg[j];
// --- repeat penalty ---
const float rp = gc.repeat_penalty;
if (std::fabs(rp - 1.0f) > 1e-6f) {
static std::vector<char> seen;
seen.assign((size_t)V, 0);
// штраф имеет смысл только за недавнюю историю, иначе O(n) на каждый токен
const size_t from = history.size() > 512 ? history.size() - 512 : 0;
for (size_t i = from; i < history.size(); ++i) {
const int id = history[i];
if (id < 0 || id >= V || seen[id]) continue;
seen[id] = 1;
lp[id] -= (rp > 1.0f) ? (rp - 1.0f) : (1.0f - 1.0f / std::max(rp, 1e-6f));
}
}
for (int j = 0; j < V; ++j) lp[j] = logits.at(j);
// --- жадный режим ---
if (gc.temperature <= 0.0f) {
int best = 0;
float bv = -1e30f;
@@ -135,116 +210,223 @@ int sample(const Tensor& logits, const GenConfig& gc, Rng& rng, const std::vecto
for (int j = 0; j < V; ++j) lp[j] /= gc.temperature;
if (gc.top_k > 0 && gc.top_k < V) {
std::vector<std::pair<float, int>> v(V);
for (int j = 0; j < V; ++j) v[j] = {lp[j], j};
std::partial_sort(v.begin(), v.begin() + gc.top_k, v.end(),
// --- top-k ---
if (gc.top_k > 0 && V > 1) {
const int k = std::min(gc.top_k, V); // было: молча выкл при V <= top_k
for (int j = 0; j < V; ++j) ord[j] = {lp[j], j};
std::partial_sort(ord.begin(), ord.begin() + k, ord.end(),
[](const std::pair<float, int>& a, const std::pair<float, int>& b) {
return a.first > b.first;
});
const float cut = v[gc.top_k].first - 1e4f;
for (int j = 0; j < V; ++j) if (lp[j] < cut) lp[j] = -1e30f;
const float cut = ord[k - 1].first; // было: ord[k] → оставалось k+1
keep.assign((size_t)V, 0);
for (int i = 0; i < k; ++i) keep[ord[i].second] = 1;
for (int j = 0; j < V; ++j) if (!keep[j]) lp[j] = -1e30f;
}
// --- softmax ---
float mx = -1e30f;
for (int j = 0; j < V; ++j) mx = std::max(mx, lp[j]);
float sum = 0.0f;
for (int j = 0; j < V; ++j) { lp[j] = std::exp(lp[j] - mx); sum += lp[j]; }
if (sum <= 0.0f) return 0;
if (!std::isfinite(mx)) return 0;
double sum = 0.0;
for (int j = 0; j < V; ++j) { lp[j] = std::expf(lp[j] - mx); sum += lp[j]; }
if (!(sum > 0.0) || !std::isfinite(sum)) return 0;
if (gc.top_p < 1.0f) {
std::vector<std::pair<float, int>> v(V);
for (int j = 0; j < V; ++j) v[j] = {lp[j] / sum, j};
std::sort(v.begin(), v.end(),
[](const std::pair<float, int>& a, const std::pair<float, int>& b) {
return a.first > b.first;
});
float acc = 0.0f;
std::vector<int> keep;
// --- top-p (nucleus) ---
if (gc.top_p > 0.0f && gc.top_p < 1.0f) {
for (int j = 0; j < V; ++j) ord[j] = {lp[j] / (float)sum, j};
std::partial_sort(ord.begin(), ord.end(), ord.end(),
[](const std::pair<float, int>& a, const std::pair<float, int>& b) {
return a.first > b.first;
});
keep.assign((size_t)V, 0);
double acc = 0.0;
for (int j = 0; j < V; ++j) {
acc += v[j].first;
keep.push_back(v[j].second);
if (acc >= gc.top_p) break;
keep[ord[j].second] = 1;
acc += ord[j].first;
if (acc >= (double)gc.top_p) break;
}
float s2 = 0.0f;
for (int j : keep) s2 += lp[j];
sum = 0.0;
for (int j = 0; j < V; ++j) {
bool in = std::find(keep.begin(), keep.end(), j) != keep.end();
lp[j] = in ? lp[j] / s2 : 0.0f;
if (keep[j]) sum += lp[j];
else lp[j] = 0.0f;
}
if (!(sum > 0.0)) return 0;
}
const float r = rng.uniform() * sum;
float acc = 0.0f;
for (int j = 0; j < V; ++j) { acc += lp[j]; if (r <= acc) return j; }
// --- выборка: lp уже нормированы на sum ---
double r = rng.uniform() * sum;
double a = 0.0;
for (int j = 0; j < V; ++j) { a += lp[j]; if (r <= a) return j; }
return V - 1;
}
// Печатать ли пробел после токена (слово vs одиночный символ).
inline bool needs_space_after(const Tokenizer& tok, int id) {
return id >= Tokenizer::n_special && id < tok.size() && tok.id2tok[id].size() > 1;
}
} // namespace gen_impl
// ===========================================================================
// generate_from — ядро: генерация продолжения из готовой истории токенов
// ===========================================================================
std::string generate_from(const Params& p, const Tokenizer& tok,
std::vector<int> history, const GenConfig& gc,
GenOutStats* st, TokenCallback on_token) {
using namespace gen_impl;
const Config& c = p.cfg;
GenOutStats dummy;
GenOutStats& S = st ? *st : dummy;
S = GenOutStats();
const int block = std::max(2, c.block_size);
// стартовая история не должна занимать весь контекст: нужен хотя бы 1 слот под генерацию
if ((int)history.size() > block - 1)
history.resize((size_t)block - 1);
if (history.empty()) history.push_back(tok.bos);
S.prompt_tokens = (int)history.size();
KvCache kv;
kv.init(c.n_layer, block, c.n_head, c.head_dim());
std::vector<float> cs, sn;
rope_tables(block, c.head_dim(), c.rope_base, cs, sn);
Rng rng(gc.seed >= 0 ? (uint64_t)gc.seed
: (uint64_t)std::chrono::steady_clock::now().time_since_epoch().count());
FwdScratch sc;
Tensor logits;
const auto t_start = std::chrono::steady_clock::now();
// порог слайда: держим 1 слот в запасе, иначе pos дорастёт до block и KvCache::off
// вылетит за границы (в 0.0.4 проверка стояла на >= block_size)
const int slide_at = block - 1;
// --- prefill: прогоняем ВЕСЬ промпт, сэмплинг не делаем ---
for (size_t i = 0; i < history.size(); ++i) {
forward_token(p, kv, sc, history[i], kv.len, cs, sn, logits);
kv.len++;
}
S.prefill_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now() - t_start).count();
const auto t_gen = std::chrono::steady_clock::now();
int feed = -1; // -1 → на первой итерации кормим последний токен промпта
for (int n = 0; n < gc.max_new_tokens; ++n) {
if (kv.len >= slide_at) {
// --- переполнение контекста: оставляем хвост и пере-префиллим ---
// (в 0.0.4 здесь было ids[i] = ids[ids.size() - keep + i] — чтение за
// границей вектора при i >= keep, плюс kv.len расходился с ids.size())
const int keep = std::max(1, block / 2);
if ((int)history.size() > keep)
history.erase(history.begin(), history.end() - keep);
kv.reset();
for (size_t i = 0; i < history.size(); ++i) {
forward_token(p, kv, sc, history[i], kv.len, cs, sn, logits);
kv.len++;
}
feed = -1;
}
if (gc.cancel && gc.cancel->load()) { S.stop_reason = "cancelled"; break; }
const int tok_in = (feed < 0) ? history.back() : feed;
forward_token(p, kv, sc, tok_in, kv.len, cs, sn, logits);
kv.len++;
const int next = sample(logits, gc, rng, history);
S.tokens.push_back(next);
feed = next;
if (next == tok.eos) { S.stop_reason = "eos"; break; }
// страховка: без маски loss у маркера <user> ненулевая вероятность,
// и модель может начать отвечать сама за себя
if (tok.has_chat_tokens() && next == tok.user) { S.stop_reason = "role"; break; }
history.push_back(next);
if (on_token) on_token(next, tok.decode_one(next));
}
if (S.stop_reason.empty())
S.stop_reason = ((int)S.tokens.size() >= gc.max_new_tokens) ? "length" : "unknown";
S.gen_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now() - t_gen).count();
if (S.gen_ns < 0) S.gen_ns = 0;
// history обрезана слайдами — наружу отдаём только промпт + сгенерированное
history.resize((size_t)S.prompt_tokens);
history.insert(history.end(), S.tokens.begin(), S.tokens.end());
std::string out;
out.reserve(S.tokens.size() * 4);
for (int id : S.tokens) {
out += tok.decode_one(id);
if (needs_space_after(tok, id)) out += " ";
}
return out;
}
// ===========================================================================
// chat_turn — один диалоговый ход
// ===========================================================================
std::string chat_turn(const Params& p, const Tokenizer& tok,
std::vector<int>& history, const std::string& user_text,
const GenConfig& gc, GenOutStats* st, TokenCallback on_token) {
if (!tok.has_chat_tokens() || tok.user < 0 || tok.asst < 0) {
if (st) { st->stop_reason = "error"; }
return "[ошибка] словарь модели не содержит <user>/<assistant> — чат невозможен. "
"Пересоздай модель командой new.";
}
if (history.empty()) history.push_back(tok.bos);
// --- подставляем маркеры и реплику пользователя ---
history.push_back(tok.user);
std::vector<int> u = tok.encode(user_text, /*add_bos=*/false);
// encode() всегда дописывает <eos> в конец (checkpoint.cpp) — срезаем,
// иначе <eos> окажется внутри реплики и генерация оборвётся на первом слове
while (!u.empty() && u.back() == tok.eos) u.pop_back();
while (!u.empty() && u.front() == tok.bos) u.erase(u.begin());
history.insert(history.end(), u.begin(), u.end());
history.push_back(tok.asst);
// --- генерируем ответ ---
const std::string answer = generate_from(p, tok, history, gc, st, on_token);
// --- фиксируем ход в истории, чтобы следующий вызов его видел ---
if (st) history.insert(history.end(), st->tokens.begin(), st->tokens.end());
history.push_back(tok.eos);
return answer;
}
// ===========================================================================
// Обратная совместимость: старый API поверх нового
// ===========================================================================
std::string generate(const Params& p, const Tokenizer& tok,
const std::string& prompt, const GenConfig& gc,
std::vector<int>* out_ids) {
const Config& c = p.cfg;
KvCache kv;
kv.init(c.n_layer, c.block_size, c.n_head, c.head_dim());
std::vector<float> cs, sn;
rope_tables(c.block_size, c.head_dim(), c.rope_base, cs, sn);
Rng rng(gc.seed >= 0 ? (uint64_t)gc.seed : 0xC0FFEEULL);
std::vector<int> ids = tok.encode(prompt, true);
if ((int)ids.size() > c.block_size) ids.resize(c.block_size);
std::vector<int> history = tok.encode(prompt, true);
TokenCallback cb;
if (gc.stream) {
std::fputs(tok.decode(ids, true).c_str(), stdout);
std::fflush(stdout);
}
std::string out = tok.decode(ids, true);
Tensor logits;
for (int n = 0; n < gc.max_new_tokens; ++n) {
if (kv.len >= c.block_size) {
const int keep = c.block_size / 2;
for (size_t i = 0; i < ids.size(); ++i)
ids[i] = ids[ids.size() - keep + i];
ids.resize(keep);
kv.reset();
for (int t = 0; t < keep; ++t) {
forward_token(p, kv, ids[t], kv.len, cs, sn, logits);
kv.len++;
}
}
const int last = ids.back();
forward_token(p, kv, last, kv.len, cs, sn, logits);
kv.len++;
int next = sample(logits, gc, rng, ids);
if (next == tok.eos) {
if (gc.stream) { std::fputc('\n', stdout); std::fflush(stdout); }
out += "\n";
ids.push_back(next);
break;
}
if (next < 0 || next >= tok.size()) next = tok.unk;
const std::string piece = tok.decode_one(next);
if (gc.stream) {
cb = [&tok](int id, const std::string& piece) {
std::fputs(piece.c_str(), stdout);
if (next >= 4 && tok.id2tok[next].size() > 1) std::fputc(' ', stdout);
if (gen_impl::needs_space_after(tok, id)) std::fputc(' ', stdout);
std::fflush(stdout);
}
out += piece;
if (next >= 4 && tok.id2tok[next].size() > 1) out += " ";
ids.push_back(next);
};
}
GenOutStats st;
const std::string text = tok.decode(history, true) + generate_from(p, tok, history, gc, &st, cb);
if (gc.stream) { std::fputc('\n', stdout); std::fflush(stdout); }
if (out_ids) *out_ids = ids;
return out;
if (out_ids) { *out_ids = history; out_ids->insert(out_ids->end(), st.tokens.begin(), st.tokens.end()); }
return text;
}
std::vector<std::string> generate_batch(const Params& p, const Tokenizer& tok,
@@ -260,4 +442,4 @@ std::vector<std::string> generate_batch(const Params& p, const Tokenizer& tok,
return out;
}
}
} // namespace xt
+48 -3
View File
@@ -1,6 +1,9 @@
// generate.h — генерация текста с KV-кэшем
// generate.h — генерация текста с KV-кэшем + диалоговый режим
#pragma once
#include "checkpoint.h"
#include <atomic>
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
@@ -11,11 +14,53 @@ struct GenConfig {
float temperature = 0.8f;
int top_k = 40;
float top_p = 0.95f;
int seed = -1;
int seed = -1; // < 0 → зерно от часов
bool stream = true;
int repeat_penalty = 1;
float repeat_penalty = 1.0f; // было int = 1, из-за чего rp-ветка никогда не срабатывала
int stop_token = -1; // -1 → использовать tok.eos
// Если указан и взведён в true — генерация прерывается на ближайшем токене.
// Нужно HTTP-серверу: клиент отвалился, считать дальше бессмысленно.
std::atomic<bool>* cancel = nullptr;
};
// Статистика одного прогона генерации.
struct GenOutStats {
int prompt_tokens = 0;
std::vector<int> tokens; // сгенерированные id (без промпта)
int64_t prefill_ns = 0;
int64_t gen_ns = 0;
std::string stop_reason; // "eos" | "role" | "length" | "error"
int n_tokens() const { return (int)tokens.size(); }
double gen_sec() const { return (double)gen_ns * 1e-9; }
double prefill_sec() const { return (double)prefill_ns * 1e-9; }
double tok_per_sec() const { double s = gen_sec(); return s > 0 ? tokens.size() / s : 0.0; }
int64_t avg_token_ns() const { return tokens.empty() ? 0 : gen_ns / (int64_t)tokens.size(); }
};
// Колбэк на каждый сгенерированный токен: (id, декодированный кусочек).
// Нужен HTTP-серверу, чтобы стримить NDJSON-чанки.
using TokenCallback = std::function<void(int id, const std::string& piece)>;
// --- ядро ---------------------------------------------------------------
// Генерация продолжения из ГОТОВОЙ истории токенов. Ничего не знает про роли:
// что положили в history, то и продолжает. history передаётся по значению.
std::string generate_from(const Params& p, const Tokenizer& tok,
std::vector<int> history, const GenConfig& gc,
GenOutStats* st = nullptr,
TokenCallback on_token = nullptr);
// --- диалог --------------------------------------------------------------
// Один ход: дописывает в history <user> …текст… <assistant>, генерирует ответ,
// останавливается на <eos> (или на <user> — страховка), дописывает ответ и <eos>
// обратно в history. history живёт между вызовами → многоходовой диалог.
std::string chat_turn(const Params& p, const Tokenizer& tok,
std::vector<int>& history, const std::string& user_text,
const GenConfig& gc,
GenOutStats* st = nullptr,
TokenCallback on_token = nullptr);
// --- старый API (обёртки над generate_from) ------------------------------
std::string generate(const Params& p, const Tokenizer& tok,
const std::string& prompt, const GenConfig& gc,
std::vector<int>* out_ids = nullptr);
+4
View File
@@ -20,6 +20,10 @@ bool Config::valid(std::string& err) const {
return false;
}
if (rope_base <= 0) { err = "rope_base должен быть > 0"; return false; }
if (n_vocab_out != 0 && n_vocab_out != -1 && n_vocab_out != vocab_size) {
err = "n_vocab_out должен быть 0 (tied), -1 (untied) или = vocab_size";
return false;
}
return true;
}
+3
View File
@@ -6,6 +6,9 @@
namespace xt {
constexpr uint32_t XNH_MAGIC = 0x31484E58;
// 1 — старая раскладка словаря (<unk> <bos> <eos> "\n")
// 2 — добавлены <user> <assistant>, "\n" переехал на id 5, в заголовке 3 новых int32
constexpr uint32_t XNH_FORMAT_VERSION = 2;
struct Config {
int vocab_size = 256;
+18 -2
View File
@@ -1,15 +1,23 @@
#pragma once
#include "model.h"
#include "checkpoint.h"
#include <cstdint>
#include <vector>
namespace xt {
// forward-declare, чтобы train.h не тянул dataset.h (и nlohmann/json) во все TU
struct ParsedDataset;
// mask == nullptr → loss по всем позициям (обычное дообучение на сплошном тексте).
// mask != nullptr → mask[i] == 1 разрешает позиции i учиться предсказывать y[i].
float backward(Params& p, const ForwardCache& fc,
const int* x, const int* y, int n_pairs);
const int* x, const int* y, int n_pairs,
const uint8_t* mask = nullptr);
float softmax_eval(const Params& p, const ForwardCache& fc,
const int* x, const int* y, int n_pairs, Tensor& per_token_loss);
const int* x, const int* y, int n_pairs, Tensor& per_token_loss,
const uint8_t* mask = nullptr);
struct TrainConfig {
int steps = 1000;
@@ -29,6 +37,7 @@ struct TrainConfig {
int ckpt_every = 0;
int val_every = 0;
int val_tokens = 20000;
bool loss_mask = false; // true → использовать маску из ParsedDataset
};
struct Dataset {
@@ -43,8 +52,15 @@ struct TrainStats {
double tokens_seen = 0;
};
// Обучение на сплошном текстовом корпусе (как было в 0.0.4).
TrainStats train_model(Params& p, const Tokenizer& tok, const std::string& corpus_path,
const TrainConfig& tc, const std::string& out_path,
int resume_step = 0);
// Дообучение на разобранном JSON-датасете диалогов (см. dataset.h).
// Сам датасет готовится parse_chat_json_file(); эта функция только учит.
TrainStats train_on_chat(Params& p, const Tokenizer& tok, const ParsedDataset& ds,
const TrainConfig& tc, const std::string& out_path,
int resume_step = 0);
}
+213 -61
View File
@@ -1,7 +1,19 @@
// trainer.cpp — цикл обучения.
//
// Изменения относительно 0.0.4:
// * вся математика шага вынесена в run_train_core() — её пользуют и
// train_model() (сплошной текст), и train_on_chat() (JSON-датасет диалогов);
// * поддержана маска loss (SFT: учим только реплики ассистента);
// * --log-every больше не игнорируется (в 0.0.4 лог печатался на КАЖДЫЙ шаг);
// * guard на resume >= steps: раньше модель перезаписывалась с откатом счётчика шагов;
// * валидация считает столько окон, сколько реально попросили (--val-tokens),
// а не захардкоженные 8.
#include "train.h"
#include "checkpoint.h"
#include "dataset.h"
#include <cstdio>
#include <cmath>
#include <cstring>
#include <fstream>
#include <sstream>
#include <chrono>
@@ -14,103 +26,151 @@ namespace {
std::string read_file(const std::string& path, bool& ok) {
std::ifstream f(path, std::ios::binary);
if (!f) { ok = false; return {}; }
std::ostringstream ss;
ss << f.rdbuf();
ok = true;
std::ostringstream ss; ss << f.rdbuf(); ok = true;
return ss.str();
}
float lr_at(const TrainConfig& tc, int step) {
if (step < tc.warmup) return tc.lr * (step + 1) / (float)std::max(1, tc.warmup);
const int t = step - tc.warmup;
if (tc.warmup > 0 && step < tc.warmup)
return tc.lr * (step + 1) / (float)std::max(1, tc.warmup);
const int t = std::max(0, step - tc.warmup);
const int total = std::max(1, tc.steps - tc.warmup);
const float f = (float)t / total;
const float cos = 0.5f * (1.0f + std::cos(3.14159265f * std::min(1.0f, f)));
return tc.lr * (tc.lr_min_frac + (1.0f - tc.lr_min_frac) * cos);
const float cs = 0.5f * (1.0f + std::cos(3.14159265f * std::min(1.0f, f)));
return tc.lr * (tc.lr_min_frac + (1.0f - tc.lr_min_frac) * cs);
}
}
TrainStats train_model(Params& p, const Tokenizer& tok, const std::string& corpus_path,
const TrainConfig& tc, const std::string& out_path,
int resume_step) {
// ---------------------------------------------------------------------------
// Единый цикл обучения.
// tokens — поток id; mask — маска loss (пустая = учим всё);
// windows — стартовые offset'ы окон длиной block (x = [w, w+block), y = [w+1, w+block+1)).
// ---------------------------------------------------------------------------
TrainStats run_train_core(Params& p, const Tokenizer& tok,
const std::vector<int>& tokens,
const std::vector<uint8_t>& mask,
const std::vector<int>& windows,
const TrainConfig& tc,
const std::string& out_path,
int resume_step) {
TrainStats st;
bool ok = false;
std::string text = read_file(corpus_path, ok);
if (!ok) { fprintf(stderr, "ошибка: не читается корпус %s\n", corpus_path.c_str()); return st; }
std::vector<int> ids = tok.encode(text, true);
if (ids.size() < 4) {
fprintf(stderr, "ошибка: корпус слишком короткий (%zu токенов)\n", ids.size());
if (windows.empty()) {
fprintf(stderr, "ошибка: нет ни одного обучающего окна\n");
return st;
}
fprintf(stderr, "корпус: %zu токенов из %zu байт\n", ids.size(), text.size());
Rng rng(tc.seed);
const int block = std::min(tc.block, p.cfg.block_size);
const int B = tc.batch_size;
if (B * (block + 1) > (int)ids.size()) {
fprintf(stderr, "ошибка: батч %d x %d не помещается в корпус\n", B, block);
const bool use_mask = tc.loss_mask && !mask.empty();
if (tc.loss_mask && mask.empty())
fprintf(stderr, "предупреждение: --mask запрошен, но маска пуста — учим все позиции\n");
// --- валидация: отрезаем хвост потока ---
std::vector<int> val_ids;
std::vector<uint8_t> val_mask;
std::vector<int> val_win;
bool has_val = false;
std::vector<int> ids = tokens;
std::vector<uint8_t> work_mask = mask;
if (tc.val_every > 0 && (int)ids.size() > tc.val_tokens + block + 1) {
const size_t split = ids.size() - (size_t)tc.val_tokens;
val_ids.assign(ids.begin() + split, ids.end());
if (use_mask) val_mask.assign(work_mask.begin() + split, work_mask.end());
ids.resize(split);
if (use_mask) work_mask.resize(split);
for (int off = 0; off + block + 1 <= (int)val_ids.size(); off += block)
val_win.push_back(off);
has_val = !val_win.empty();
if (has_val)
fprintf(stderr, "валидация: %zu токенов, %zu окон\n", val_ids.size(), val_win.size());
}
// --- пересобираем окна после того, как хвост ушёл в валидацию ---
std::vector<int> train_win;
train_win.reserve(windows.size());
for (int w : windows) if (w + block + 1 <= (int)ids.size()) train_win.push_back(w);
if (train_win.empty()) {
fprintf(stderr, "ошибка: после отделения валидации не осталось обучающих окон\n");
return st;
}
if ((int)train_win.size() < B)
fprintf(stderr, "предупреждение: окон %d меньше батча %d — данные будут повторяться\n",
(int)train_win.size(), B);
std::vector<int> val_ids;
bool has_val = false;
if (tc.val_every > 0 && ids.size() > (size_t)tc.val_tokens + block + 1) {
val_ids.assign(ids.end() - tc.val_tokens, ids.end());
ids.resize(ids.size() - tc.val_tokens);
has_val = true;
fprintf(stderr, "валидация: %zu токенов\n", val_ids.size());
}
fprintf(stderr, "обучающих окон: %zu (блок %d, поток %zu токенов), маска loss: %s\n",
train_win.size(), block, ids.size(), use_mask ? "да" : "нет");
std::vector<int> xb((size_t)B * block), yb((size_t)B * block);
std::vector<uint8_t> mb((size_t)B * block, 1);
std::vector<int> xb(B * block), yb(B * block);
ForwardCache fc;
auto t0 = std::chrono::steady_clock::now();
const int start = resume_step;
if (start >= tc.steps) {
fprintf(stderr, "ошибка: resume-шаг %d >= --steps %d, обучать нечего\n", start, tc.steps);
return st;
}
for (int step = start; step < tc.steps; ++step) {
for (int b = 0; b < B; ++b) {
size_t off = rng.below(ids.size() - block - 1);
for (int t = 0; t < block; ++t) {
xb[b * block + t] = ids[off + t];
yb[b * block + t] = ids[off + t + 1];
}
const int off = train_win[rng.below(train_win.size())];
int* xd = xb.data() + (size_t)b * block;
int* yd = yb.data() + (size_t)b * block;
uint8_t* md = mb.data() + (size_t)b * block;
// x[t] = ids[off+t], y[t] = ids[off+t+1], mask[t] = mask[off+t+1]
// (mask[i] относится к предсказанию ids[i+1], поэтому берём со сдвигом)
std::memcpy(xd, ids.data() + off, (size_t)block * sizeof(int));
std::memcpy(yd, ids.data() + off + 1, (size_t)block * sizeof(int));
if (use_mask) std::memcpy(md, work_mask.data() + off + 1, (size_t)block * sizeof(uint8_t));
else std::memset(md, 1, (size_t)block);
}
forward(p, xb.data(), B * block, block, fc);
float loss = backward(p, fc, xb.data(), yb.data(), B * block);
float loss = backward(p, fc, xb.data(), yb.data(), B * block,
use_mask ? mb.data() : nullptr);
p.adam_step(lr_at(tc, step), tc.beta1, tc.beta2, tc.eps,
tc.weight_decay, step + 1, tc.clip);
st.loss = loss;
st.step = step;
st.step = step + 1;
st.tokens_seen += (double)B * block;
auto now = std::chrono::steady_clock::now();
double dt = std::chrono::duration<double>(now - t0).count();
double tps = dt > 0 ? st.tokens_seen / dt : 0;
fprintf(stderr, "шаг %5d/%d loss %.4f ppl %8.2f lr %.2e %6.0f ток/с\n",
step, tc.steps, loss, std::exp(loss), lr_at(tc, step), tps);
if (tc.val_every > 0 && has_val && (step + 1) % tc.val_every == 0) {
float vl = 0;
const int nwin = 8;
for (int w = 0; w < nwin; ++w) {
size_t off = (val_ids.size() - block - 1) * w / nwin;
std::vector<int> vx(block);
for (int t = 0; t < block; ++t) vx[t] = val_ids[off + t];
forward(p, vx.data(), block, block, fc);
Tensor lg;
softmax_eval(p, fc, vx.data(), val_ids.data() + off + 1, block, lg);
for (int t = 0; t < block; ++t) vl += lg.at(t);
}
st.val_loss = vl / (nwin * block);
fprintf(stderr, " val loss %.4f ppl %.2f\n", st.val_loss, std::exp(st.val_loss));
// --- лог: в 0.0.4 tc.log_every читался, но не использовался ---
const bool last = (step + 1 == tc.steps);
if (tc.log_every > 0 && ((step + 1) % tc.log_every == 0 || last)) {
const double dt = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
const double tps = dt > 0 ? st.tokens_seen / dt : 0;
fprintf(stderr, "шаг %5d/%d loss %.4f ppl %8.2f lr %.2e %6.0f ток/с\n",
step + 1, tc.steps, loss, std::exp(loss), lr_at(tc, step), tps);
}
// --- валидация ---
if (has_val && tc.val_every > 0 && ((step + 1) % tc.val_every == 0 || last)) {
double vl = 0; int nw = 0;
Tensor lg;
std::vector<int> vx((size_t)block);
std::vector<uint8_t> vm((size_t)block, 1);
for (int off : val_win) {
for (int t = 0; t < block; ++t) {
vx[t] = val_ids[(size_t)off + t];
vm[t] = use_mask ? val_mask[(size_t)off + t + 1] : 1;
}
forward(p, vx.data(), block, block, fc);
softmax_eval(p, fc, vx.data(), val_ids.data() + off + 1, block, lg,
use_mask ? vm.data() : nullptr);
for (int t = 0; t < block; ++t) vl += lg.at(t);
++nw;
}
st.val_loss = nw ? (float)(vl / ((double)nw * block)) : 0.0f;
fprintf(stderr, " val loss %.4f ppl %.2f (окон %d)\n",
st.val_loss, std::exp(st.val_loss), nw);
}
// --- промежуточный чекпоинт ---
if (tc.ckpt_every > 0 && (step + 1) % tc.ckpt_every == 0 && step + 1 < tc.steps) {
Checkpoint ck{p, tok, step + 1, loss, tc.seed};
std::string path = out_path + ".step" + std::to_string(step + 1);
@@ -131,4 +191,96 @@ TrainStats train_model(Params& p, const Tokenizer& tok, const std::string& corpu
return st;
}
} // namespace
// ===========================================================================
// Обучение на сплошном текстовом корпусе (прежнее поведение)
// ===========================================================================
TrainStats train_model(Params& p, const Tokenizer& tok, const std::string& corpus_path,
const TrainConfig& tc, const std::string& out_path,
int resume_step) {
bool ok = false;
std::string text = read_file(corpus_path, ok);
if (!ok) { fprintf(stderr, "ошибка: не читается корпус %s\n", corpus_path.c_str()); return {}; }
std::vector<int> ids = tok.encode(text, true);
if (ids.size() < 4) {
fprintf(stderr, "ошибка: корпус слишком короткий (%zu токенов)\n", ids.size());
return {};
}
fprintf(stderr, "корпус: %zu токенов из %zu байт\n", ids.size(), text.size());
const int block = std::min(tc.block, p.cfg.block_size);
const int B = tc.batch_size;
if (B <= 0 || block <= 0) { fprintf(stderr, "ошибка: batch и block должны быть > 0\n"); return {}; }
if ((size_t)B * ((size_t)block + 1) > ids.size()) {
fprintf(stderr, "ошибка: батч %d x %d не помещается в корпус (%zu токенов)\n",
B, block, ids.size());
return {};
}
TrainConfig cfg = tc;
cfg.block = block;
cfg.loss_mask = false;
std::vector<int> windows;
for (int off = 0; off + block + 1 <= (int)ids.size(); off += block) windows.push_back(off);
return run_train_core(p, tok, ids, {}, windows, cfg, out_path, resume_step);
}
// ===========================================================================
// Дообучение на JSON-датасете диалогов
// ===========================================================================
TrainStats train_on_chat(Params& p, const Tokenizer& tok, const ParsedDataset& ds,
const TrainConfig& tc, const std::string& out_path,
int resume_step) {
if (!ds.ok()) { fprintf(stderr, "ошибка датасета: %s\n", ds.error.c_str()); return {}; }
if (ds.samples.empty()) { fprintf(stderr, "ошибка: в датасете нет диалогов\n"); return {}; }
const int block = std::min(tc.block, p.cfg.block_size);
if (tc.batch_size <= 0 || block <= 0) { fprintf(stderr, "ошибка: batch и block должны быть > 0\n"); return {}; }
std::vector<int> ids;
std::vector<uint8_t> mask;
std::vector<int> windows;
if (ds.cfg.pack_mode == 0) {
// Поток: <bos> …<eos> <bos> …<eos>, окна нарезаны парсером.
ids = ds.stream;
mask = ds.smask;
windows = ds.windows;
for (int& w : windows) if (w + block + 1 > (int)ids.size()) w = -1;
windows.erase(std::remove(windows.begin(), windows.end(), -1), windows.end());
} else {
// Строка на диалог: перекладываем rows (шаг block) в поток с шагом block+1,
// чтобы x/y-срезы не вылезали за конец буфера.
const int n = ds.n_samples;
ids.assign((size_t)n * ((size_t)block + 1), tok.eos);
mask.assign((size_t)n * ((size_t)block + 1), 0);
for (int i = 0; i < n; ++i) {
const size_t src = (size_t)i * (size_t)block;
const size_t dst = (size_t)i * ((size_t)block + 1);
for (int t = 0; t < block; ++t) {
ids[dst + (size_t)t] = ds.rows[src + (size_t)t];
mask[dst + (size_t)t] = ds.rowmask[src + (size_t)t];
}
ids[dst + (size_t)block] = tok.eos;
mask[dst + (size_t)block] = 0;
windows.push_back((int)dst);
}
}
if (windows.empty()) {
fprintf(stderr, "ошибка: после подгонки block=%d не осталось окон (датасет слишком короткий)\n", block);
return {};
}
TrainConfig cfg = tc;
cfg.block = block;
cfg.loss_mask = ds.cfg.loss_mask;
return run_train_core(p, tok, ids, mask, windows, cfg, out_path, resume_step);
}
} // namespace xt
+853 -3
View File
@@ -1,5 +1,855 @@
// handler.cpp — реализация Ollama-совместимого HTTP-сервера для Xenith.
//
// Created by koder on 30.09.2026.
//
// Особенности реализации:
// * ядро Xenith однопоточное и НЕ потокобезопасное (общий ForwardCache,
// статические буферы в sample()), поэтому генерация сериализована g_gen_mtx;
// * модели хранятся в shared_ptr<const Checkpoint> — снимок на запрос стоит
// копейки, а гонки при удалении модели невозможны;
// * стриминг НАСТОЯЩИЙ: контент-провайдер cpp-httplib вызывается в том же
// потоке, что и handler, поэтому генерация вынесена в отдельный поток,
// а провайдер блокируется на condition_variable с таймаутом. При разрыве
// соединения взводится GenConfig::cancel и генерация прерывается;
// * /api/pull, /api/push и /api/blobs/:digest возвращают 501 — реестра
// моделей у Xenith нет, модель создаётся через /api/create FROM <путь>.
#include "handler.h"
#include "../core/checkpoint.h"
#include "../core/generate.h"
#include "../core/model.h"
#include <atomic>
#include <cctype>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <exception>
#include <filesystem>
#include <fstream>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include "../libs/cpp-httplib-0.57.1/httplib.h"
#include "../libs/json-3.12.0/nlohmann/json.hpp"
using json = nlohmann::json;
namespace fs = std::filesystem;
namespace xt {
namespace {
constexpr const char* XENITH_VERSION = "0.0.4";
constexpr const char* CREATED_AT = "1970-01-01T00:00:00Z";
// ---------------------------------------------------------------------------
// Реестр моделей
// ---------------------------------------------------------------------------
struct Entry {
std::string name;
std::string path;
std::shared_ptr<const Checkpoint> ck; // nullptr, пока не загружена
std::string load_err;
};
std::map<std::string, Entry> g_models; // ключ — имя без ":latest"
std::string g_default;
std::mutex g_registry_mtx;
std::mutex g_gen_mtx; // сериализация генерации
bool g_verbose = false;
std::string strip_tag(const std::string& n) {
const size_t p = n.find(':');
return (p == std::string::npos) ? n : n.substr(0, p);
}
std::string display_name(const std::string& n) {
return n.find(':') == std::string::npos ? n + ":latest" : n;
}
uint64_t file_size_or(const std::string& path, uint64_t fallback) {
std::error_code ec;
const auto sz = fs::file_size(path, ec);
return ec ? fallback : (uint64_t)sz;
}
std::string digest_of(const std::string& path) {
char buf[32];
snprintf(buf, sizeof buf, "%016zx", std::hash<std::string>{}(path));
return buf;
}
// ---------------------------------------------------------------------------
// Конфиг
// ---------------------------------------------------------------------------
bool parse_conf(const std::string& path, OllamaOptions& opt,
std::vector<std::pair<std::string,std::string>>& models) {
std::ifstream f(path);
if (!f) return false;
std::ostringstream ss; ss << f.rdbuf();
const std::string text = ss.str();
// 1) JSON
try {
json j = json::parse(text);
if (j.contains("host") && j["host"].is_string()) opt.host = j["host"].get<std::string>();
if (j.contains("port") && j["port"].is_number_integer()) opt.port = j["port"].get<int>();
if (j.contains("default_model") && j["default_model"].is_string()) opt.default_model = j["default_model"].get<std::string>();
if (j.contains("verbose") && j["verbose"].is_boolean()) opt.verbose = j["verbose"].get<bool>();
if (j.contains("scan_models_dir") && j["scan_models_dir"].is_boolean()) opt.scan_models_dir = j["scan_models_dir"].get<bool>();
if (j.contains("models") && j["models"].is_array()) {
for (const auto& m : j["models"]) {
std::string n = m.value("name", "");
std::string p = m.value("path", "");
if (n.empty() && !p.empty()) n = fs::path(p).stem().string();
if (!n.empty() && !p.empty()) models.emplace_back(n, p);
}
}
return true;
} catch (const std::exception&) { /* не JSON — пробуем простой формат */ }
// 2) "key: value", модели строками "model: name = path"
std::istringstream ls(text);
std::string line;
while (std::getline(ls, line)) {
const size_t c = line.find(':');
if (c == std::string::npos) continue;
std::string k = line.substr(0, c), v = line.substr(c + 1);
auto trim = [](std::string& s) {
size_t a = 0, b = s.size();
while (a < b && std::isspace((unsigned char)s[a])) ++a;
while (b > a && std::isspace((unsigned char)s[b-1])) --b;
s = s.substr(a, b - a);
};
trim(k); trim(v);
if (k == "host") opt.host = v;
else if (k == "port") opt.port = std::atoi(v.c_str());
else if (k == "default_model") opt.default_model = v;
else if (k == "verbose") opt.verbose = (v == "true" || v == "1");
else if (k == "model" || k == "models") {
const size_t eq = v.find('=');
if (eq != std::string::npos) models.emplace_back(v.substr(0, eq), v.substr(eq + 1));
else models.emplace_back(fs::path(v).stem().string(), v);
}
}
return true;
}
void scan_models_dir(std::vector<std::pair<std::string,std::string>>& models) {
std::error_code ec;
if (!fs::is_directory("models", ec)) return;
for (const auto& e : fs::directory_iterator("models", ec)) {
if (!e.is_regular_file() || e.path().extension() != ".xnh") continue;
const std::string n = e.path().stem().string();
bool dup = false;
for (auto& m : models) if (m.first == n) { dup = true; break; }
if (!dup) models.emplace_back(n, e.path().string());
}
}
// ---------------------------------------------------------------------------
// Доступ к модели (ленивая загрузка). Возвращает снимок — после него
// g_registry_mtx можно не держать.
// ---------------------------------------------------------------------------
struct ModelRef {
std::shared_ptr<const Checkpoint> ck;
std::string name; // имя без тега
std::string path;
bool valid = false;
};
ModelRef acquire(const std::string& wanted, std::string& err) {
ModelRef out;
std::lock_guard<std::mutex> lk(g_registry_mtx);
std::string name = strip_tag(wanted.empty() ? g_default : wanted);
if (name.empty()) {
if (g_models.empty()) { err = "no models registered"; return out; }
name = g_models.begin()->first;
}
auto it = g_models.find(name);
if (it == g_models.end()) {
// может, передали путь к файлу?
std::error_code ec;
if (!wanted.empty() && fs::exists(wanted, ec) && fs::path(wanted).extension() == ".xnh") {
const std::string stem = fs::path(wanted).stem().string();
it = g_models.find(stem);
if (it == g_models.end()) it = g_models.emplace(stem, Entry{}).first;
it->second.name = stem;
it->second.path = wanted;
name = it->first;
} else {
err = "model '" + (wanted.empty() ? std::string("<default>") : wanted) + "' not found";
return out;
}
}
Entry& e = it->second;
if (!e.ck) {
auto ck = std::make_shared<Checkpoint>();
if (load_checkpoint(e.path, *ck, e.load_err)) {
e.ck = ck;
if (g_verbose)
fprintf(stderr, "[ollama] загружена %s (%s, %.2f М параметров)\n",
e.name.c_str(), e.path.c_str(), ck->params.n_params() / 1048576.0);
} else {
err = "failed to load '" + e.path + "': " + e.load_err;
return out;
}
}
out.ck = e.ck; out.name = e.name; out.path = e.path; out.valid = true;
return out;
}
// ---------------------------------------------------------------------------
// JSON-хелперы
// ---------------------------------------------------------------------------
std::string jdump(const json& j) { return j.dump(); }
json err_json(const std::string& msg) { return json{{"error", msg}}; }
bool jbool(const json& j, const char* k, bool def) {
return (j.contains(k) && j[k].is_boolean()) ? j[k].get<bool>() : def;
}
std::string jstr(const json& j, const char* k, const std::string& def = "") {
return (j.contains(k) && j[k].is_string()) ? j[k].get<std::string>() : def;
}
// значение из тела запроса ИЛИ из вложенного "options" (у Ollama настройки там)
template <typename T> T jopt(const json& j, const char* k, T def);
template <> int jopt<int>(const json& j, const char* k, int def) {
if (j.contains("options") && j["options"].is_object() && j["options"].contains(k) && j["options"][k].is_number())
return j["options"][k].get<int>();
if (j.contains(k) && j[k].is_number()) return j[k].get<int>();
return def;
}
template <> float jopt<float>(const json& j, const char* k, float def) {
if (j.contains("options") && j["options"].is_object() && j["options"].contains(k) && j["options"][k].is_number())
return (float)j["options"][k].get<double>();
if (j.contains(k) && j[k].is_number()) return (float)j[k].get<double>();
return def;
}
template <> bool jopt<bool>(const json& j, const char* k, bool def) {
if (j.contains("options") && j["options"].is_object() && j["options"].contains(k) && j["options"][k].is_boolean())
return j["options"][k].get<bool>();
if (j.contains(k) && j[k].is_boolean()) return j[k].get<bool>();
return def;
}
GenConfig build_gen_config(const json& j) {
GenConfig gc;
gc.max_new_tokens = jopt<int>(j, "num_predict", 256);
if (gc.max_new_tokens <= 0) gc.max_new_tokens = 1 << 20; // -1 у Ollama = без лимита
if (gc.max_new_tokens > (1 << 20)) gc.max_new_tokens = 1 << 20;
gc.temperature = jopt<float>(j, "temperature", 0.8f);
gc.top_k = jopt<int>(j, "top_k", 40);
gc.top_p = jopt<float>(j, "top_p", 0.95f);
gc.repeat_penalty = jopt<float>(j, "repeat_penalty", 1.0f);
gc.seed = jopt<int>(j, "seed", -1);
gc.stream = false; // стримингом занимается сервер
return gc;
}
// "stop" бывает строкой или массивом строк
std::vector<std::string> build_stop(const json& j) {
std::vector<std::string> out;
const json* s = nullptr;
if (j.contains("options") && j["options"].is_object() && j["options"].contains("stop")) s = &j["options"]["stop"];
else if (j.contains("stop")) s = &j["stop"];
if (!s) return out;
if (s->is_string()) out.push_back(s->get<std::string>());
else if (s->is_array()) for (auto& e : *s) if (e.is_string()) out.push_back(e.get<std::string>());
return out;
}
// Кусочек текста для стрима: после многосимвольного токена (слова) нужен пробел,
// после одиночного символа — нет. Тот же правило, что в Tokenizer::decode.
std::string piece_out(const Tokenizer& tok, int id, const std::string& piece) {
if (id >= Tokenizer::n_special && id < tok.size() && tok.id2tok[id].size() > 1)
return piece + " ";
return piece;
}
// Если ответ содержит стоп-слово — обрезаем по нему (и чанки тоже).
void apply_stop_words(std::string& text, const std::vector<std::string>& stops) {
if (stops.empty()) return;
size_t cut = std::string::npos;
for (const auto& s : stops) {
if (s.empty()) continue;
const size_t p = text.find(s);
if (p != std::string::npos && p < cut) cut = p;
}
if (cut != std::string::npos) text.resize(cut);
}
// ---------------------------------------------------------------------------
// Описание модели в формате Ollama
// ---------------------------------------------------------------------------
json model_details(const Entry& e) {
const Config& c = e.ck->params.cfg;
return json{
{"parent_model", ""},
{"format", "xnh"},
{"family", "xenith"},
{"families", json::array({"xenith"})},
{"parameter_size", std::to_string(e.ck->params.n_params())},
{"quantization_level", "F32"},
{"xenith", {
{"layers", c.n_layer}, {"heads", c.n_head}, {"embedding_dim", c.n_embd},
{"ffn_dim", c.ffn()}, {"vocab_size", c.vocab_size}, {"block_size", c.block_size},
{"rope_base", c.rope_base}, {"tied", e.ck->params.tied()},
{"chat_capable", e.ck->tok.has_chat_tokens() && e.ck->tok.user >= 0}
}}
};
}
json model_card(const Entry& e) {
return json{
{"name", display_name(e.name)},
{"model", display_name(e.name)},
{"modified_at", CREATED_AT},
{"size", file_size_or(e.path, e.ck ? e.ck->params.n_params() * 4 : 0)},
{"digest", digest_of(e.path)},
{"details", e.ck ? model_details(e) : json{{"format", "xnh"}}}
};
}
// ---------------------------------------------------------------------------
// Настоящий стриминг: продюсер в отдельном потоке, провайдер блокируется на cv.
// ---------------------------------------------------------------------------
struct StreamBuf {
std::mutex m;
std::condition_variable cv;
std::deque<std::string> q;
bool done = false;
std::string final_json;
std::atomic<bool> cancel{false};
std::chrono::steady_clock::time_point last_pull = std::chrono::steady_clock::now();
};
void start_stream(httplib::Response& res, std::shared_ptr<StreamBuf> sb,
std::function<void(std::shared_ptr<StreamBuf>)> producer) {
std::thread([sb, producer]() {
try { producer(sb); }
catch (...) {
std::lock_guard<std::mutex> lk(sb->m);
sb->final_json = jdump(err_json("internal error during generation"));
}
{ std::lock_guard<std::mutex> lk(sb->m); sb->done = true; }
sb->cv.notify_all();
}).detach();
res.set_chunked_content_provider(
"application/x-ndjson",
[sb](size_t /*offset*/, httplib::DataSink& sink) -> bool {
std::unique_lock<std::mutex> lk(sb->m);
// ждём чанк не дольше 5 секунд за раз, чтобы заметить разрыв соединения
sb->cv.wait_for(lk, std::chrono::seconds(5),
[&]{ return !sb->q.empty() || sb->done; });
sb->last_pull = std::chrono::steady_clock::now();
if (!sb->q.empty()) {
const std::string c = sb->q.front();
sb->q.pop_front();
lk.unlock();
if (!sink.write(c.data(), c.size())) { sb->cancel = true; return false; }
return true;
}
if (sb->done) {
const std::string f = sb->final_json;
lk.unlock();
sb->cancel = true;
if (!f.empty() && !sink.write(f.data(), f.size())) return false;
sink.done();
return false;
}
// продюсер ещё считает (например, длинный prefill) — тянем пустой keep-alive
lk.unlock();
return true;
});
}
// ---------------------------------------------------------------------------
// Обработчики
// ---------------------------------------------------------------------------
void h_version(const httplib::Request&, httplib::Response& res) {
res.set_content(jdump(json{{"version", XENITH_VERSION}}), "application/json");
}
void h_health(const httplib::Request&, httplib::Response& res) {
res.set_content(jdump(json{{"status", "ok"}, {"version", XENITH_VERSION}}), "application/json");
}
void h_tags(const httplib::Request&, httplib::Response& res) {
std::lock_guard<std::mutex> lk(g_registry_mtx);
json arr = json::array();
for (auto& kv : g_models) arr.push_back(model_card(kv.second));
res.set_content(jdump(json{{"models", arr}}), "application/json");
}
void h_ps(const httplib::Request&, httplib::Response& res) {
std::lock_guard<std::mutex> lk(g_registry_mtx);
json arr = json::array();
for (auto& kv : g_models) {
const Entry& e = kv.second;
if (!e.ck) continue;
const uint64_t sz = e.ck->params.n_params() * 4;
arr.push_back(json{
{"name", display_name(e.name)}, {"model", display_name(e.name)},
{"size", sz}, {"digest", digest_of(e.path)},
{"details", model_details(e)},
{"expires_at", CREATED_AT}, {"size_vram", sz}
});
}
res.set_content(jdump(json{{"models", arr}}), "application/json");
}
void h_show(const httplib::Request& req, httplib::Response& res) {
json body;
try { body = req.body.empty() ? json::object() : json::parse(req.body); }
catch (...) { res.status = 400; res.set_content(jdump(err_json("invalid json")), "application/json"); return; }
std::string err;
ModelRef m = acquire(jstr(body, "model"), err);
if (!m.valid) { res.status = 404; res.set_content(jdump(err_json(err)), "application/json"); return; }
Entry e; e.name = m.name; e.path = m.path; e.ck = m.ck;
json out = model_card(e);
out["license"] = "MIT";
out["system"] = "";
out["template"] = "<bos><user>{{ .Prompt }}<assistant>";
out["modelfile"] = std::string("# Xenith model\nFROM ") + m.path;
out["parameters"] = "temperature 0.8\ntop_k 40\ntop_p 0.95\n";
out["model_info"] = model_details(e)["xenith"];
out["capabilities"] = (m.ck->tok.has_chat_tokens() && m.ck->tok.user >= 0)
? json::array({"completion", "embeddings"})
: json::array({"completion"});
res.set_content(jdump(out), "application/json");
}
void h_create(const httplib::Request& req, httplib::Response& res) {
json body;
try { body = req.body.empty() ? json::object() : json::parse(req.body); }
catch (...) { res.status = 400; res.set_content(jdump(err_json("invalid json")), "application/json"); return; }
const std::string name = jstr(body, "model", jstr(body, "name"));
if (name.empty()) { res.status = 400; res.set_content(jdump(err_json("model name required")), "application/json"); return; }
// ищем "FROM <путь>" в modelfile
std::string path;
{
std::istringstream ls(jstr(body, "modelfile"));
std::string line;
while (std::getline(ls, line)) {
size_t a = 0;
while (a < line.size() && std::isspace((unsigned char)line[a])) ++a;
if (line.size() > a + 5 && line.compare(a, 5, "FROM ") == 0) { path = line.substr(a + 5); break; }
}
}
while (!path.empty() && std::isspace((unsigned char)path.back())) path.pop_back();
std::error_code ec;
if (path.empty() || !fs::exists(path, ec)) {
res.status = 400;
res.set_content(jdump(err_json("modelfile must contain 'FROM <path-to-.xnh>' and that file must exist")),
"application/json");
return;
}
{
std::lock_guard<std::mutex> lk(g_registry_mtx);
Entry& e = g_models[strip_tag(name)];
e.name = strip_tag(name);
e.path = path;
e.ck.reset();
e.load_err.clear();
if (g_default.empty()) g_default = e.name;
}
std::string err;
if (!acquire(name, err).valid) {
res.status = 500; res.set_content(jdump(err_json(err)), "application/json"); return;
}
res.set_content(jdump(json{{"status", "success"}}), "application/json");
}
void h_delete(const httplib::Request& req, httplib::Response& res) {
json body;
try { body = req.body.empty() ? json::object() : json::parse(req.body); }
catch (...) { res.status = 400; res.set_content(jdump(err_json("invalid json")), "application/json"); return; }
const std::string name = strip_tag(jstr(body, "model", jstr(body, "name")));
std::lock_guard<std::mutex> lk(g_registry_mtx);
auto it = g_models.find(name);
if (it == g_models.end()) {
res.status = 404; res.set_content(jdump(err_json("model '" + name + "' not found")), "application/json");
return;
}
g_models.erase(it);
if (g_default == name) g_default = g_models.empty() ? "" : g_models.begin()->first;
res.status = 200;
res.set_content("", "application/json");
}
void h_not_implemented(const httplib::Request&, httplib::Response& res) {
res.status = 501;
res.set_content(jdump(err_json(
"Xenith не работает с реестром моделей: зарегистрируй модель через "
"POST /api/create с 'FROM <путь к .xnh>' или положи файл в каталог models/")),
"application/json");
}
// --- /api/generate ---------------------------------------------------------
void h_generate(const httplib::Request& req, httplib::Response& res) {
json body;
try { body = req.body.empty() ? json::object() : json::parse(req.body); }
catch (...) { res.status = 400; res.set_content(jdump(err_json("invalid json")), "application/json"); return; }
std::string err;
ModelRef m = acquire(jstr(body, "model"), err);
if (!m.valid) { res.status = 404; res.set_content(jdump(err_json(err)), "application/json"); return; }
const std::string prompt = jstr(body, "prompt");
const bool stream = jbool(body, "stream", true);
const bool raw = jbool(body, "raw", false);
const GenConfig gc = build_gen_config(body);
const std::vector<std::string> stops = build_stop(body);
auto producer = [m, prompt, gc, stops, raw](std::shared_ptr<StreamBuf> sb) {
std::lock_guard<std::mutex> gen_lk(g_gen_mtx);
const std::string model = display_name(m.name);
GenConfig g = gc;
g.cancel = &sb->cancel;
std::vector<int> history = raw ? m.ck->tok.encode(prompt, false)
: m.ck->tok.encode(prompt, true);
while (!history.empty() && history.back() == m.ck->tok.eos) history.pop_back();
if (history.empty()) history.push_back(m.ck->tok.bos);
GenOutStats st;
std::string running; // накопленный текст — для поиска стоп-слов
// Чанк уходит сразу; при срабатывании стоп-слова взводим cancel, а лишний
// хвост вырезается из итогового текста через apply_stop_words().
TokenCallback cb = [&](int id, const std::string& piece) {
const std::string chunk = piece_out(m.ck->tok, id, piece);
running += chunk;
for (const auto& s : stops) {
if (!s.empty() && running.find(s) != std::string::npos) { sb->cancel = true; break; }
}
{
std::lock_guard<std::mutex> lk(sb->m);
sb->q.push_back(jdump(json{{"model", model}, {"created_at", CREATED_AT},
{"response", chunk}, {"done", false}}) + "\n");
}
sb->cv.notify_one();
};
std::string text = generate_from(m.ck->params, m.ck->tok, history, g, &st, cb);
apply_stop_words(text, stops);
json fin = {
{"model", model}, {"created_at", CREATED_AT},
{"response", text}, {"done", true}, {"done_reason", st.stop_reason},
{"total_duration", st.prefill_ns + st.gen_ns}, {"load_duration", 0},
{"prompt_eval_count", st.prompt_tokens}, {"prompt_eval_duration", st.prefill_ns},
{"eval_count", st.n_tokens()}, {"eval_duration", st.gen_ns}
};
std::lock_guard<std::mutex> lk(sb->m);
sb->final_json = jdump(fin) + "\n";
};
if (stream) { start_stream(res, std::make_shared<StreamBuf>(), producer); return; }
// --- нестриминговый путь: считаем синхронно ---
auto sb = std::make_shared<StreamBuf>();
producer(sb);
res.set_content(sb->final_json.empty() ? jdump(err_json("generation failed")) : sb->final_json,
"application/json");
}
// --- /api/chat -------------------------------------------------------------
void h_chat(const httplib::Request& req, httplib::Response& res) {
json body;
try { body = req.body.empty() ? json::object() : json::parse(req.body); }
catch (...) { res.status = 400; res.set_content(jdump(err_json("invalid json")), "application/json"); return; }
std::string err;
ModelRef m = acquire(jstr(body, "model"), err);
if (!m.valid) { res.status = 404; res.set_content(jdump(err_json(err)), "application/json"); return; }
if (!body.contains("messages") || !body["messages"].is_array()) {
res.status = 400;
res.set_content(jdump(err_json("\"messages\" must be an array of {role, content}")), "application/json");
return;
}
if (!m.ck->tok.has_chat_tokens() || m.ck->tok.user < 0) {
res.status = 400;
res.set_content(jdump(err_json("model '" + m.name + "' has no <user>/<assistant> tokens — "
"chat is impossible; run `xenith fine-tune` first")), "application/json");
return;
}
const bool stream = jbool(body, "stream", true);
const bool raw = jbool(body, "raw", false);
const GenConfig gc = build_gen_config(body);
const std::vector<std::string> stops = build_stop(body);
// Разбираем messages. Отдельного токена <system> в словаре Xenith нет,
// поэтому системный промпт приклеивается к последней user-реплике.
std::string system_text, last_user;
std::vector<std::pair<std::string,std::string>> prior;
for (const auto& msg : body["messages"]) {
if (!msg.is_object()) continue;
std::string role = msg.value("role", "");
const std::string text = msg.value("content", "");
for (auto& ch : role) ch = (char)std::tolower((unsigned char)ch);
if (role == "system") {
system_text += (system_text.empty() ? "" : "\n") + text;
} else if (role == "user") {
if (!last_user.empty()) prior.emplace_back("user", last_user);
last_user = text;
} else if (role == "assistant") {
if (!last_user.empty()) { prior.emplace_back("user", last_user); last_user.clear(); }
prior.emplace_back("assistant", text);
}
// "tool" и прочие роли Xenith не поддерживает — пропускаем
}
std::string turn_text = system_text.empty() ? last_user : system_text + "\n" + last_user;
auto producer = [m, prior, turn_text, gc, stops, raw](std::shared_ptr<StreamBuf> sb) {
std::lock_guard<std::mutex> gen_lk(g_gen_mtx);
const std::string model = display_name(m.name);
GenConfig g = gc;
g.cancel = &sb->cancel;
std::string text;
GenOutStats st;
if (raw) {
std::string joined;
for (const auto& pr : prior) joined += pr.second + "\n";
joined += turn_text;
text = generate_from(m.ck->params, m.ck->tok, m.ck->tok.encode(joined, true), g, &st, nullptr);
} else {
std::vector<int> history{m.ck->tok.bos};
// предыдущие ходы: user-реплики прогоняем через chat_turn с нулевой
// генерацией (нужно лишь правильно пополнить history), assistant-реплики
// кладём как есть — модель их не порождает.
GenConfig pre = g;
pre.max_new_tokens = 0;
pre.cancel = nullptr;
for (const auto& pr : prior) {
if (pr.first == "user") {
chat_turn(m.ck->params, m.ck->tok, history, pr.second, pre, nullptr, nullptr);
} else {
history.push_back(m.ck->tok.asst);
auto ids = m.ck->tok.encode(pr.second, false);
while (!ids.empty() && ids.back() == m.ck->tok.eos) ids.pop_back();
history.insert(history.end(), ids.begin(), ids.end());
history.push_back(m.ck->tok.eos);
}
}
std::string running;
TokenCallback cb = [&](int id, const std::string& piece) {
const std::string chunk = piece_out(m.ck->tok, id, piece);
running += chunk;
for (const auto& s : stops) {
if (!s.empty() && running.find(s) != std::string::npos) { sb->cancel = true; break; }
}
{
std::lock_guard<std::mutex> lk(sb->m);
sb->q.push_back(jdump(json{{"model", model}, {"created_at", CREATED_AT},
{"message", {{"role","assistant"}, {"content", chunk}}}, {"done", false}}) + "\n");
}
sb->cv.notify_one();
};
text = chat_turn(m.ck->params, m.ck->tok, history, turn_text, g, &st, cb);
}
apply_stop_words(text, stops);
json fin = {
{"model", model}, {"created_at", CREATED_AT},
{"message", {{"role", "assistant"}, {"content", text}}},
{"done", true}, {"done_reason", st.stop_reason},
{"total_duration", st.prefill_ns + st.gen_ns}, {"load_duration", 0},
{"prompt_eval_count", st.prompt_tokens}, {"prompt_eval_duration", st.prefill_ns},
{"eval_count", st.n_tokens()}, {"eval_duration", st.gen_ns}
};
std::lock_guard<std::mutex> lk(sb->m);
sb->final_json = jdump(fin) + "\n";
};
if (stream) { start_stream(res, std::make_shared<StreamBuf>(), producer); return; }
auto sb = std::make_shared<StreamBuf>();
producer(sb);
res.set_content(sb->final_json.empty() ? jdump(err_json("generation failed")) : sb->final_json,
"application/json");
}
// --- /api/embed, /api/embeddings -------------------------------------------
void h_embed(const httplib::Request& req, httplib::Response& res) {
json body;
try { body = req.body.empty() ? json::object() : json::parse(req.body); }
catch (...) { res.status = 400; res.set_content(jdump(err_json("invalid json")), "application/json"); return; }
std::string err;
ModelRef m = acquire(jstr(body, "model"), err);
if (!m.valid) { res.status = 404; res.set_content(jdump(err_json(err)), "application/json"); return; }
std::vector<std::string> inputs;
if (body.contains("input")) {
if (body["input"].is_string()) inputs.push_back(body["input"].get<std::string>());
else if (body["input"].is_array())
for (auto& x : body["input"]) if (x.is_string()) inputs.push_back(x.get<std::string>());
}
if (inputs.empty() && body.contains("prompt") && body["prompt"].is_string())
inputs.push_back(body["prompt"].get<std::string>());
if (inputs.empty()) {
res.status = 400; res.set_content(jdump(err_json("\"input\" (string or array) required")), "application/json");
return;
}
const Params& p = m.ck->params;
const int d = p.cfg.n_embd;
json embeddings = json::array();
json tokens_used = json::array();
for (const auto& text : inputs) {
std::vector<int> ids = m.ck->tok.encode(text, false);
while (!ids.empty() && ids.back() == m.ck->tok.eos) ids.pop_back();
std::vector<float> acc((size_t)d, 0.0f);
for (int id : ids) {
if (id < 0 || id >= p.wte.R()) continue;
const float* row = p.wte.row(id);
for (int j = 0; j < d; ++j) acc[(size_t)j] += row[j];
}
const float n = ids.empty() ? 1.0f : (float)ids.size();
for (auto& x : acc) x /= n;
double sq = 0; for (float x : acc) sq += (double)x * x;
const float inv = sq > 0 ? (float)(1.0 / std::sqrt(sq)) : 0.0f;
for (auto& x : acc) x *= inv;
embeddings.push_back(acc);
tokens_used.push_back((int)ids.size());
}
if (req.path == "/api/embeddings") { // старый формат Ollama
res.set_content(jdump(json{{"embedding", embeddings.empty() ? json::array() : embeddings[0]}}),
"application/json");
return;
}
res.set_content(jdump(json{
{"model", display_name(m.name)},
{"embeddings", embeddings},
{"total_duration", 0}, {"load_duration", 0},
{"prompt_eval_count", tokens_used}
}), "application/json");
}
// --- служебные -------------------------------------------------------------
void h_root(const httplib::Request&, httplib::Response& res) {
std::string list;
size_t n = 0;
{
std::lock_guard<std::mutex> lk(g_registry_mtx);
n = g_models.size();
for (auto& kv : g_models)
list += " " + display_name(kv.second.name) + " -> " + kv.second.path +
(kv.second.ck ? " [loaded]" : "") + "\n";
}
res.set_content(
std::string("Xenith ") + XENITH_VERSION + " — Ollama-compatible API\n\n"
"GET /api/version /api/tags /api/ps /health\n"
"POST /api/show /api/create /api/delete\n"
"POST /api/generate /api/chat /api/embed /api/embeddings\n"
"501 /api/pull /api/push /api/blobs/:digest (реестра моделей нет)\n\n"
"models (" + std::to_string(n) + "):\n" +
(list.empty() ? " (пусто — положи .xnh в models/ или сделай POST /api/create)\n" : list),
"text/plain; charset=utf-8");
}
void logger(const httplib::Request& req, const httplib::Response& res) {
if (!g_verbose) return;
fprintf(stderr, "[ollama] %s %s -> %d\n", req.method.c_str(), req.path.c_str(), res.status);
}
} // namespace
// ===========================================================================
int run_ollama_server(const OllamaOptions& opt_in) {
OllamaOptions opt = opt_in;
std::vector<std::pair<std::string,std::string>> found;
if (!opt.conf.empty()) {
if (!parse_conf(opt.conf, opt, found)) {
fprintf(stderr, "ollama: не читается конфиг %s\n", opt.conf.c_str());
return 1;
}
fprintf(stderr, "ollama: конфиг %s\n", opt.conf.c_str());
}
if (opt.scan_models_dir) scan_models_dir(found);
g_verbose = opt.verbose;
{
std::lock_guard<std::mutex> lk(g_registry_mtx);
for (auto& m : found) {
Entry& e = g_models[strip_tag(m.first)];
e.name = strip_tag(m.first);
e.path = m.second;
}
g_default = strip_tag(opt.default_model);
if (g_default.empty() && !g_models.empty()) g_default = g_models.begin()->first;
}
if (g_models.empty())
fprintf(stderr, "ollama: моделей не найдено. Положи .xnh в ./models/ или задай --conf\n");
httplib::Server svr;
svr.set_logger(logger);
svr.set_payload_max_length(64 * 1024 * 1024); // в 0.57.1 метод называется именно так
svr.Get ("/api/version", h_version);
svr.Get ("/api/tags", h_tags);
svr.Get ("/api/ps", h_ps);
svr.Post("/api/show", h_show);
svr.Post("/api/create", h_create);
svr.Post("/api/delete", h_delete);
svr.Post("/api/pull", h_not_implemented);
svr.Post("/api/push", h_not_implemented);
svr.Post("/api/generate", h_generate);
svr.Post("/api/chat", h_chat);
svr.Post("/api/embed", h_embed);
svr.Post("/api/embeddings", h_embed);
svr.Get (R"(/api/blobs/(.+))", h_not_implemented);
svr.Get ("/", h_root);
svr.Get ("/health", h_health);
fprintf(stderr, "Xenith Ollama API: http://%s:%d (моделей: %zu, по умолчанию: %s)\n",
opt.host.c_str(), opt.port, g_models.size(),
g_default.empty() ? "<нет>" : g_default.c_str());
fprintf(stderr, "проверка: curl http://%s:%d/api/tags\n", opt.host.c_str(), opt.port);
if (!svr.listen(opt.host, opt.port)) {
fprintf(stderr, "ollama: не удалось занять %s:%d\n", opt.host.c_str(), opt.port);
return 1;
}
return 0;
}
} // namespace xt
+44 -7
View File
@@ -1,13 +1,50 @@
#ifndef XENITH_HANDLER_H
#define XENITH_HANDLER_H
// handler.h — HTTP-сервер, совместимый с Ollama API.
//
// Реализованы все эндпоинты Ollama:
// GET /api/version
// GET /api/tags список моделей
// POST /api/show параметры/шаблон конкретной модели
// POST /api/create регистрация модели по пути к .xnh
// POST /api/delete выгрузка из реестра
// POST /api/pull 501 (реестра Xenith не существует)
// POST /api/push 501
// GET /api/ps загруженные модели
// POST /api/generate генерация продолжения (+stream NDJSON)
// POST /api/chat диалог в формате messages (+stream NDJSON)
// POST /api/embed эмбеддинги (среднее wte по токенам, L2-норма)
// POST /api/embeddings то же, старый формат Ollama
// GET /api/blobs/:digest 501
// GET / служебная страница
// GET /health проверка живости
//
// Конфиг (--conf NAME.conf) — JSON или простые пары "key: value":
// {
// "host": "127.0.0.1",
// "port": 11434,
// "default_model": "bipy",
// "models": [ {"name": "bipy", "path": "models/bipy.xnh"}, … ]
// }
// Если конфига нет — сканируется каталог models/ на *.xnh.
#pragma once
namespace api
{
class handler
{
#include <string>
};
}
namespace xt {
struct OllamaOptions {
std::string conf; // путь к конфигу (--conf)
std::string host = "127.0.0.1";
int port = 11434;
std::string default_model; // какая модель отвечает, если в запросе нет "model"
bool scan_models_dir = true; // подхватывать models/*.xnh без конфига
bool verbose = false;
};
#endif //XENITH_HANDLER_H
// Заблокировать порт и обслуживать запросы. Возвращает код ошибки (0 = отработал).
int run_ollama_server(const OllamaOptions& opt);
} // namespace xt
#endif // XENITH_HANDLER_H
+1 -1
View File
@@ -4,7 +4,7 @@
#include <vector>
#include <string>
#include "libs/cpp-httplib-0.57.1/httplib.h"
#include "libs/json-3.12.0/single_include/nlohmann/json.hpp"
#include "libs/json-3.12.0/nlohmann/json.hpp"
using json = nlohmann::json;