From c86b4a774cdd4620e3023642242b1c1d6a1771d3 Mon Sep 17 00:00:00 2001 From: Axelaredz <1193738+Axelaredz@users.noreply.github.com> Date: Wed, 14 Oct 2026 01:23:32 +0000 Subject: [PATCH] Fix custom-model wizard flow and modernize capability-aware tuning Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .gitignore | 3 + README.md | 16 +- bin/llamastery | 19 +- docs/ru/upstream-2026-10-14.md | 291 +++++++ lib/axes.py | 48 +- lib/budget.py | 9 +- lib/launch.py | 128 +++ lib/measure.py | 5 +- lib/schema.py | 27 +- lib/wizard.py | 200 +++-- .../upstream-2026-10-14-bench-help.txt | 19 + .../upstream-2026-10-14-server-help.txt | 25 + tests/run_tests.py | 457 +++++++++- tools/tune_models.py | 781 ++++++++++++++---- 14 files changed, 1761 insertions(+), 267 deletions(-) create mode 100644 docs/ru/upstream-2026-10-14.md create mode 100644 lib/launch.py create mode 100644 tests/fixtures/upstream-2026-10-14-bench-help.txt create mode 100644 tests/fixtures/upstream-2026-10-14-server-help.txt diff --git a/.gitignore b/.gitignore index 18bc831..944b4a2 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,6 @@ dist/ .DS_Store .idea/ .vscode/ + +# Local upstream review/download cache +.cache/ diff --git a/README.md b/README.md index 61cfb07..9e9e592 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,21 @@ bin/llamastery # мастер настройки (или Мастер: состояние → «что делаем?» (роутер/свап/пресет — только то, что сейчас возможно) → сборка → swap → модели → пресет → контекст → зрение → ускорители → план. На любом экране `0` — вернуться на шаг назад. -Модели, которой нет в пресете, можно указать прямо в мастере: в конце списка пресетов есть пункт `▸ свой .gguf — указать путь`, но достаточно и вставить путь к `.gguf` прямо в вопрос со списком. Мастер прочитает файл, спросит, чьи флаги копировать, и допишет новую секцию в `models.ini` (с бэкапом). +Модели, которой нет в пресете, можно указать прямо в мастере: в конце списка пресетов есть пункт `▸ свой .gguf — указать путь`, но достаточно и вставить путь к `.gguf` прямо в вопрос со списком. Мастер прочитает файл и предложит создать секцию **без копирования чужого пресета** (по умолчанию) либо взять существующий за основу. Затем можно ввести собственные флаги `llama-server`, например: + +```text +--chat-template-file '/models/my template.jinja' --rope-scaling yarn +``` + +Флаги проверяются по `--help` выбранной сборки; неизвестные ключи, пропущенные значения и управляющие параметры (`--model`, `--port` и т. п.) отклоняются. Кавычки, пробелы и `ключ=значение` сохраняются. Повтор одного флага с разными значениями не поддерживается форматом пресета — мастер сообщит об этом, а не потеряет значение. Соседний `mmproj` подключается только с подтверждением. После просмотра параметров и согласия секция записывается в `models.ini` с бэкапом; отсутствие самого ini не мешает создать первый пресет. + +**Флаги сервера и параметры тюнера — разные вещи:** первые хранятся в секции модели, вторые передаются через `tune … --extra`. Тюнер учитывает глобальные `[*]`, алиасы и нестандартные флаги выбранной сборки. Для дополнительных флагов, которые предварительный `llama-bench` не воспроизводит, поиск идёт через `llama-server` (это может быть медленнее). Контекст и ускоритель из плана применяются после подтверждения; результаты самого подбора автоматически не записываются. Ошибка проверки или tune останавливает мастер. + +Обновление tune от 14.10.2026: [обзор 152 upstream-коммитов за неделю и новые оси](docs/ru/upstream-2026-10-14.md). +Staged теперь ограничивает общий бюджет поиска, измеряет исходный пресет и +проверяет `moe-cache-mib` / `threads-batch` только при поддержке сборки. +`cpu-ffn-values`, `op-offload-values`, `repack-values`, `backend-sampling-values` +включаются явно; неподдерживаемые оси не имитируются в `llama-bench`. Подобрать параметры пресета автоматически (долго, грузит GPU — запускай в свободное время): diff --git a/bin/llamastery b/bin/llamastery index 15fc6dd..0d9ae63 100755 --- a/bin/llamastery +++ b/bin/llamastery @@ -19,7 +19,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) -from lib import (axes, budget, builds, crashes, gguf, i18n, measure, paths, # noqa: E402 +from lib import (axes, budget, builds, crashes, gguf, i18n, launch, measure, paths, # noqa: E402 presets, runtime, schema, server, swap, validate, wizard) from lib.i18n import t # noqa: E402 from lib.inifile import IniFile # noqa: E402 @@ -674,7 +674,7 @@ def cmd_validate(args) -> int: sec = ini.section(name) if not sec: continue - pairs = sec.pairs() + pairs = launch.effective_pairs(ini, name, flags) meta_hit = validate.validate_section(name, pairs, flags, rep, check_paths=not args.no_paths, model_cache=cache) @@ -722,7 +722,7 @@ def cmd_budget(args) -> int: sec = ini.section(name) if not sec: continue - pairs = sec.pairs() + pairs = launch.effective_pairs(ini, name) model = pairs.get("model") or pairs.get("m") or "" meta = None mp = pairs.get("mmproj") @@ -756,7 +756,7 @@ def cmd_budget(args) -> int: tg = meas.get("deep_tps") or meas.get("short_tps") or "" tg = f"{tg:.0f} t/s" if isinstance(tg, (int, float)) else "" print(f"{name[:43]:<44} {est.weights_gb:8.2f}G {est.kv_gb:7.2f}G " - f"{est.mmproj_gb:6.2f}G {est.compute_gb:7.2f}G {est.total_gb:8.2f}G {tg:>9}") + f"{est.mmproj_gb:6.2f}G {est.compute_gb + est.moe_cache_gb:7.2f}G {est.total_gb:8.2f}G {tg:>9}") # прогноз против --models-max budget_mib = vram or int(cal.get("vram_total_mib", 0) or 0) @@ -1182,8 +1182,9 @@ def cmd_tune(args) -> int: if not binary: print(t('не найден llama-server; укажи --build'), file=sys.stderr) return 1 - cmd = [sys.executable, str(tuner), args.ini, args.section, - "--server", str(binary)] + ini_path = Path(args.ini).expanduser().resolve() + cmd = [sys.executable, str(tuner), str(ini_path), args.section, + "--server", str(binary.resolve())] for item in args.extra: if "=" in item: k, v = item.split("=", 1) @@ -1192,11 +1193,13 @@ def cmd_tune(args) -> int: cmd.append(f"--{item.lstrip('-')}") # артефакты прогона (tune-results/) должны ложиться рядом с пресетом, # а не в каталог, откуда запущен скилл - run_dir = Path(args.ini).expanduser().parent + run_dir = ini_path.parent print(t('запуск:'), " ".join(cmd), file=sys.stderr) print(t('рабочий каталог: {0}', run_dir), file=sys.stderr) try: - return subprocess.call(cmd, cwd=str(run_dir)) + build = builds.get(src) + env = server.build_env(build) if build else None + return subprocess.call(cmd, cwd=str(run_dir), env=env) except OSError as exc: print(t('не удалось запустить тюнер: {0}', exc), file=sys.stderr) return 1 diff --git a/docs/ru/upstream-2026-10-14.md b/docs/ru/upstream-2026-10-14.md new file mode 100644 index 0000000..d9501ec --- /dev/null +++ b/docs/ru/upstream-2026-10-14.md @@ -0,0 +1,291 @@ +# llama.cpp: неделя 7–14 октября 2026 и обновление tune + +## Срез и воспроизводимость + +Проверен **ggml-org/llama.cpp**, основная ветка, через GitHub API: **152 коммита** с +7 октября 00:00 MSK до доступного на момент проверки состояния 14 октября. +Время проверки — около 04:11 MSK. Срез: [`fcac19079f3f`](https://github.com/ggml-org/llama.cpp/commit/fcac19079f3f2985fe74ed845f0880e7e9a8030a). +База сравнения `common/arg.cpp` перед первым коммитом периода: +[`5ad1c5da0ad7`](https://github.com/ggml-org/llama.cpp/commit/5ad1c5da0ad7f6176256b823925aad19134f0263). +Это не обзор будущих изменений до конца 14 октября. + +Сверены список коммитов, патчи ключевых изменений, `common/arg.cpp`, +`tools/llama-bench/llama-bench.cpp` и server README в обоих срезах. +Список всех 152 коммитов приведён ниже; подробно разобраны изменения, +относящиеся к параметрам запуска и измерениям. Не каждый backend-патч проверялся запуском. + +## Что изменилось upstream + +| Изменение | Значение для tune | +|---|---| +| [#29887, 7 октября: GPU-кэш MoE-экспертов из host memory](https://github.com/ggml-org/llama.cpp/pull/29887) | Добавлен **`--moe-cache-mib N`**, env `LLAMA_ARG_MOE_CACHE_MIB`. Это дополнительная VRAM, а не бесплатный ускоритель. Есть смысл при CPU-offload экспертов, не на dense-модели. | +| [#30112, 8 октября: multi-GPU MoE cache](https://github.com/ggml-org/llama.cpp/pull/30112) | Бюджет кэша распределяется между GPU подобно слоям через `tensor-split`. Pipeline parallelism отключается при включённом кэше. Не следует автоматически ожидать ускорения на нескольких GPU. | +| [#28331, 9 октября: llama-bench учитывает `-fitc`](https://github.com/ggml-org/llama.cpp/pull/28331) | При auto-fit берётся максимум требуемых тестом токенов и `fit_min_ctx`. `--fit-ctx` — **минимум для fit**, не замена `--ctx-size`. В актуальном bench нет `--ctx-size`, есть `--n-depth`. | +| [#30223, 9 октября: статическая backend-sampling graph между ubatch](https://github.com/ggml-org/llama.cpp/pull/30223) | Исправлена топология графа, в том числе для сборок `GGML_SCHED_NO_REALLOC`. Уже существующий экспериментальный `--backend-sampling` имеет смысл перепроверить, но только явным A/B. | +| [#28713, 8 октября: CUDA top-k algorithm selection](https://github.com/ggml-org/llama.cpp/pull/28713) | Выбор CUDA-алгоритма изменён внутри backend. Это **не новый CLI-флаг** и не причина подменять пользовательский `top-k` ради красивой скорости. | +| [#30103, 10 октября: CUDA/HIP Flash Attention race](https://github.com/ggml-org/llama.cpp/pull/30103) | Исправление корректности; старые результаты FA на другой сборке нельзя считать эквивалентными новым. | +| [#30257, 10 октября: MTP с multimodal input](https://github.com/ggml-org/llama.cpp/pull/30257), [#30397, 13 октября](https://github.com/ggml-org/llama.cpp/pull/30397) | Изменения совместимости vision/MTP. Обычный текстовый tune не доказывает корректность картинок и MTP. | +| [#30272, 10 октября: `LLAMA_ARG_SLOT_SAVE_PATH`](https://github.com/ggml-org/llama.cpp/pull/30272) | Новый env-алиас к существующему `--slot-save-path`; не ось производительности. | +| [#30159, 9 октября: server port 9931](https://github.com/ggml-org/llama.cpp/pull/30159) | Тюнер уже выделяет свободный порт и передаёт его явно, поэтому смена upstream-дефолта не требует смены его порта. | + +По diff `common/arg.cpp` за этот период новый параметр производительности — +именно **`--moe-cache-mib`**. `n-cpu-ffn`, `threads-batch`, `op-offload`, `repack`, +`backend-sampling` ниже — актуальные существовавшие ранее параметры, а не +якобы добавленные за эту неделю. + +В проверенном `llama-bench` **нет** `moe-cache-mib`, `n-cpu-ffn`, +`threads-batch`, `backend-sampling`. Передавать их туда или считать замер без +них проверкой этой оси нельзя. `op-offload` в bench задаётся как +`--no-op-offload 0|1`, `repack` — `--repack 0|1`; у сервера это переключатели +с положительной/отрицательной формами. + +## Исправленные недостатки поиска + +- Метка `_axis` входила в ключ конфигурации: одинаковые параметры, полученные + разными путями, могли измеряться заново. Теперь ключ нормализует метаданные, + числовое написание, bool и неявный V=K. +- Исходный пресет отсутствовал среди screening-кандидатов. Теперь контрольная + точка измеряется первой; без bench серверный поиск тоже стартует от пресета. +- `max-screen` ограничивал первый список, но не уточнения. Теперь это общий + лимит, включая baseline, неудачные пробы и refinement. Часть бюджета + резервируется под уточнение, варианты чередуются между осями. +- Staged-поиск без bench превращался в перебор дефолтов MoE×ubatch. Теперь это + поиск вокруг лучшей серверной конфигурации с общим `max-candidates`. +- В staged больше нет двойной загрузки каждой модели для отдельного короткого + предфильтра и полной проверки. Короткий retrieval и затем deep выполняются + на одном сервере; провал retrieval останавливает глубокую пробу. +- Оси фильтруются отдельно для server/bench и MoE/dense. Число offload-слоёв + ограничено метаданными. Неизвестная архитектура не включает MoE-ось наугад. +- Убрана связка «изменить decode threads → молча изменить prefill threads». + Разные типы K/V в исходном пресете сохраняются, логический batch сравнивается + с его фактическим значением. +- Quantized V при `fa=off` не порождает заведомо неработающих кандидатов. + Это не доказывает поддержку каждого квантованного типа конкретным backend: + runtime-проверка остаётся необходимой. +- `fit=off` фиксируется в серверных прогонах, если сборка его поддерживает: + auto-fit не должен тайком менять проверяемое размещение. При `--apply` этот + параметр также сохраняется. Auto-fit bench доступен только явным запросом. +- Приоритеты осей больше не учатся на сравнении разных моделей, контекстов и + зарегистрированных build fingerprint. Fingerprint — путь/размер/mtime + бинаря, **не** криптографическая аттестация всех библиотек и железа. + +## Новые оси и ограничения + +| CLI тюнера | Что проверяется | По умолчанию | +|---|---|---| +| `--moe-cache-values auto` или `0,256,512,1024` | `--moe-cache-mib` | `auto`: 0/256/512 MiB, только подтверждённая MoE и доступный флаг; ненулевые варианты — при host-экспертах | +| `--threads-batch-values auto` или `4,8,16` | `--threads-batch` | `auto`: текущее, половина и все логические CPU; число физических ядер не угадывается | +| `--cpu-ffn-values 0,4,8` | `--n-cpu-ffn` | выключено; только dense | +| `--op-offload-values on,off` | `--op-offload` / `--no-op-offload` | выключено, явный A/B | +| `--repack-values on,off` | `--repack` / `--no-repack` | выключено, явный A/B | +| `--backend-sampling-values off,on` | `--backend-sampling` | выключено, экспериментальный server-only A/B | +| `--kv-values q8_0,f16` | пара K/V | существующая политика, пока список не задан | +| `--bench-fit-target 1024` | bench fit margin + `--fit-ctx` | 0: auto-fit не включается | + +Новые оси — для **`search=staged`**. `full` оставлен legacy-сеткой; явный запрос +новых осей с `full` отклоняется, а не игнорируется. Ограниченный бюджет не +обещает проверить каждое значение каждой оси — фактически выбранные параметры +записываются в `plan.json`, `screening.json`, `results.json`. + +VRAM MoE-кэша добавлена в budget и в идентификатор измерения. Рост кэша +ограничивается наблюдаемым запасом лучшего успешного кандидата, сохраняя +`reserve`. Это предварительный отсев, не гарантия отсутствия OOM. + +## Примеры + +MoE с частью экспертов в RAM, короткий ограниченный поиск: + +```bash +llamastery tune ~/.config/llama/models.ini my-moe --build upstream \ + --extra search=staged search-ctx=16384 \ + moe-values=16,20,24 moe-cache-values=0,256,512 \ + threads-batch-values=4,8,16 max-screen=12 max-candidates=12 +``` + +Список `moe-values` надо выбирать в пределах числа слоёв своей модели. +Нестандартные флаги самой модели остаются в её INI-секции, не в `--extra`. + +Отдельная кампания экспериментальных переключателей: + +```bash +llamastery tune ~/.config/llama/models.ini my-model --build upstream \ + --extra search=staged search-ctx=8192 skip-screening \ + op-offload-values=on,off repack-values=on,off \ + backend-sampling-values=off,on max-candidates=12 +``` + +Запись победителя — только после полной проверки: отдельный запуск с +`--extra deep apply`, без уменьшенного `search-ctx`. Автоматическая запись +после короткого поиска по-прежнему запрещена. + +## Проверка и границы результатов + +Пройдены `python tests/run_tests.py` (82 теста) и проверка синтаксиса/CLI help. +Добавлены небольшие fixtures деклараций актуального server/bench help, +проверки capability gating, argv, apply, VRAM, дедупликации и mock-кампания, +проходящая через `main()` без запуска GPU и настоящего сервера. + +**Аппаратного A/B здесь не было: ускорение в процентах не заявляется.** +Пробы retrieval используют синтетический повторяющийся текст. Для MoE-кэша, +MTP и backend sampling это не замена тесту на реальном workload. При нескольких +GPU текущий монитор тюнера наблюдает выбранный `--gpu`; распределение кэша +upstream поддерживает, но суммарный reserve по всем картам этот тест не доказывает. + +## Все коммиты периода + +Время ниже — UTC из GitHub (`committer.date`); граница выборки выше — MSK. + +| UTC | Коммит | Изменение | +|---|---|---| +| 2026-10-13T23:24:23Z | [fcac19079f3f](https://github.com/ggml-org/llama.cpp/commit/fcac19079f3f2985fe74ed845f0880e7e9a8030a) | webgpu: (Fix CI) fix mul_mat_id with duplicate expert ids (#30451) | +| 2026-10-13T23:17:11Z | [04f7226a2c12](https://github.com/ggml-org/llama.cpp/commit/04f7226a2c12c7f382c545a6db5a034266aa53cb) | server : escape the special tokens without std::regex (#30243) | +| 2026-10-13T23:03:56Z | [ff026f8c0a97](https://github.com/ggml-org/llama.cpp/commit/ff026f8c0a97fe80649f34763432c9d40b418622) | chat: replace output string with parts (#30389) | +| 2026-10-13T18:22:19Z | [1b70350c9256](https://github.com/ggml-org/llama.cpp/commit/1b70350c92563449576bcbbf552994b1d1ed847d) | ggml : simplify backend search path error handling (#28367) | +| 2026-10-13T18:20:41Z | [d71e324a44ce](https://github.com/ggml-org/llama.cpp/commit/d71e324a44ce1238bdb066e58b88d629c5b49254) | docs : update zDNN supported ops (#30472) | +| 2026-10-13T16:37:48Z | [45451c366d42](https://github.com/ggml-org/llama.cpp/commit/45451c366d4256f94fbc8845645e31a6b9155054) | kleidiai: add SME2 Q4_K and Q6_K matmul support (#29219) | +| 2026-10-13T15:17:59Z | [77c4540ce466](https://github.com/ggml-org/llama.cpp/commit/77c4540ce4667f4577753fe034a3a8042f510b8f) | vulkan: Optimize pool_2d when the pooling window is large (#30119) | +| 2026-10-13T14:58:35Z | [ecdd29e8b207](https://github.com/ggml-org/llama.cpp/commit/ecdd29e8b2076bb85da9e9ca7ee3d84264375bd1) | meta: recreate all subgraphs when the arena is reallocated (#30453) | +| 2026-10-13T14:47:55Z | [ec0bfac1794a](https://github.com/ggml-org/llama.cpp/commit/ec0bfac1794ad722221dd68d84760f8980355fb2) | hexagon: add configurable HTP DCVS/HMX power mode (#30423) | +| 2026-10-13T14:34:10Z | [ace20f679e30](https://github.com/ggml-org/llama.cpp/commit/ace20f679e30a39c09a7b17bec14199855469633) | graph: pad the KQ bias of the no-cache attention (#30446) | +| 2026-10-13T14:28:15Z | [b9f3599fb1c4](https://github.com/ggml-org/llama.cpp/commit/b9f3599fb1c429e89248f042699ea2e062a32e57) | llama : do not map foreign ranges into a backend buffer (#30405) | +| 2026-10-13T14:18:01Z | [f441d2d9db68](https://github.com/ggml-org/llama.cpp/commit/f441d2d9db68410f78b9e937efe479049f458044) | model: load YaRN beta metadata for laguna models (#30331) | +| 2026-10-13T14:16:14Z | [cb55ffe6e214](https://github.com/ggml-org/llama.cpp/commit/cb55ffe6e2147eb15f4bede1f60d11246715754f) | graph: skip the LM head for pooled embeddings (#30445) | +| 2026-10-13T13:21:55Z | [a17e94d229fc](https://github.com/ggml-org/llama.cpp/commit/a17e94d229fc7fed1567a799baebd11b771fe5af) | tests : consolidate context state tests into test-llama-context (#30023) | +| 2026-10-13T13:07:54Z | [b476d9a762d6](https://github.com/ggml-org/llama.cpp/commit/b476d9a762d64a9ef8e82ee59419eca495a24b51) | llama : fix log message (#30452) | +| 2026-10-13T13:05:10Z | [e0bcaccbe50a](https://github.com/ggml-org/llama.cpp/commit/e0bcaccbe50a773c8addec49bbfc8b7ba953c63b) | vulkan: allow multiple devices to access gpu-visible host memory (#29741) | +| 2026-10-13T12:36:47Z | [0a731cced9ed](https://github.com/ggml-org/llama.cpp/commit/0a731cced9ed826349838333a767ccae63164c2c) | ggml-cpu : add AVX2 dot product for Q2_0 (#30447) | +| 2026-10-13T12:24:34Z | [f851e244d0dc](https://github.com/ggml-org/llama.cpp/commit/f851e244d0dc56074ab701c4467edb116840cb88) | cuda : add GGML_CUDA_GRAPH_DEBUG and read env vars once (#30327) | +| 2026-10-13T11:48:49Z | [bfe65e1dfa8f](https://github.com/ggml-org/llama.cpp/commit/bfe65e1dfa8f1afed8a2158e83e5d2a3d6db5444) | cuda : fix compiler warnings in mmq-load-tiles.cuh (#30443) | +| 2026-10-13T11:03:47Z | [411d54851501](https://github.com/ggml-org/llama.cpp/commit/411d548515017ca75c2a12c39659b6e7e1551dd7) | vulkan : split matmul dispatch when it would exceed maxComputeWorkGroupCount (#29533) | +| 2026-10-13T10:39:10Z | [296538adea19](https://github.com/ggml-org/llama.cpp/commit/296538adea19ff397100bf8e7d71f302d2d2bb35) | spec : remove tokens assert from dsv4 graph_mtp (#30444) | +| 2026-10-13T10:34:47Z | [7f51953d7d2f](https://github.com/ggml-org/llama.cpp/commit/7f51953d7d2f359939a763549e93d51f0347e569) | model : allow Qwen3.8 Flash Next to accept image embds for MTP (#30397) | +| 2026-10-13T10:29:27Z | [882d67166d23](https://github.com/ggml-org/llama.cpp/commit/882d67166d237a7020c21c6e35fe05f00f92cb6d) | cuda : fix warnings from dead breaks (#30441) | +| 2026-10-13T09:44:37Z | [30f7df1a831b](https://github.com/ggml-org/llama.cpp/commit/30f7df1a831ba5bda37b737f46bdf2f11f6bcb88) | cuda : warnings cleanup (#30420) | +| 2026-10-13T08:29:09Z | [9d7d5049804b](https://github.com/ggml-org/llama.cpp/commit/9d7d5049804be03fce6575cc9f49c058b3c48788) | convert : fix LoRA conversion with --outtype auto (#30433) | +| 2026-10-13T08:24:20Z | [ed019cd8b94a](https://github.com/ggml-org/llama.cpp/commit/ed019cd8b94a8194881e3d2448075156939d32a1) | llama : skip logits buffer allocation when graph produces no logits (#30255) | +| 2026-10-13T08:22:19Z | [98801578818b](https://github.com/ggml-org/llama.cpp/commit/98801578818b26d833a1fe244870d64b0c34bb46) | graph : avoid reallocations in the "no cache" path (#30439) | +| 2026-10-13T07:53:48Z | [af50f2f248b4](https://github.com/ggml-org/llama.cpp/commit/af50f2f248b475d9760f8e67503d01c0f194f5f4) | ggml-zdnn : introduce Q8_0 mat mul (#29836) | +| 2026-10-13T07:26:52Z | [071b553fb1d3](https://github.com/ggml-org/llama.cpp/commit/071b553fb1d3a1b76c0b12ab9a1546714cafe4e1) | models : remove redundant ggml_cont calls now supported by all unary kernels (#30198) | +| 2026-10-13T03:33:05Z | [4413a192410f](https://github.com/ggml-org/llama.cpp/commit/4413a192410fad1f054e9216114087a3e01527a0) | hexagon: extend scalar DMA broadcasting support for binary ops (#30245) | +| 2026-10-13T02:22:05Z | [8f574b0ad44c](https://github.com/ggml-org/llama.cpp/commit/8f574b0ad44c46d7b499ec028c29205aaa3fe80f) | ci : build OpenVINO releases with GGML_NATIVE=OFF and CPU backend variants (#30324) | +| 2026-10-13T02:20:04Z | [a49f58dcc3af](https://github.com/ggml-org/llama.cpp/commit/a49f58dcc3af1aa869b2287bb71953d0ad0395e4) | ci: fix OpenVINO download links (#30401) | +| 2026-10-12T22:23:01Z | [cbe28bb3cb07](https://github.com/ggml-org/llama.cpp/commit/cbe28bb3cb0758f0c566a9a3561766821aeb0748) | model: fix vllm d3 multi seq case (#30408) | +| 2026-10-12T21:00:27Z | [358a420ec4ed](https://github.com/ggml-org/llama.cpp/commit/358a420ec4ed59b6b0be08b1d1f71dd478b99a99) | graph: pad the KV dimension of the no-cache attention to 256 (#30416) | +| 2026-10-12T19:57:26Z | [48e985756788](https://github.com/ggml-org/llama.cpp/commit/48e985756788b4a6c50933a88e0af1aa8412b68d) | metal: fix metal tensor kernel_mul_mm error for large tensor (#28748) | +| 2026-10-12T14:39:55Z | [8bb3cf0d216a](https://github.com/ggml-org/llama.cpp/commit/8bb3cf0d216a5ae48360179f2931daf284be4d01) | hexagon: optimize CPY/CONCAT — round 3, short-rows edition (#30341) | +| 2026-10-12T14:19:20Z | [0f701c882986](https://github.com/ggml-org/llama.cpp/commit/0f701c88298606b41a13268a027e97c877ff63ca) | vulkan: pack FMA for f16 accumulation, no dot product op (#29877) | +| 2026-10-12T13:01:52Z | [efe3626b119f](https://github.com/ggml-org/llama.cpp/commit/efe3626b119ff81033e309c3ba07a770bef2c546) | model: support vllm d3 models (#30383) | +| 2026-10-12T11:39:55Z | [097cf33d9499](https://github.com/ggml-org/llama.cpp/commit/097cf33d9499b1eade67d51e16d7c75427e7b267) | model: support vllm decision 2 model (#30378) | +| 2026-10-12T10:32:56Z | [ccdbe290533f](https://github.com/ggml-org/llama.cpp/commit/ccdbe290533f68154ede46e0618622eebcb6c070) | tests : link each test against only the libraries it uses (#30299) | +| 2026-10-12T10:31:41Z | [073b74034b8b](https://github.com/ggml-org/llama.cpp/commit/073b74034b8bfe652e410ec8bd1e0d95a7d46fea) | metal : fix mul_mat_id with duplicate ids (#30373) | +| 2026-10-12T10:02:24Z | [77757a34672a](https://github.com/ggml-org/llama.cpp/commit/77757a34672a888845a09ab45728b8d34aa475ff) | examples : fix draft sampling and rejection handling (#30095) | +| 2026-10-12T08:53:58Z | [972b5fcc1967](https://github.com/ggml-org/llama.cpp/commit/972b5fcc19670e597f8de9bf5cacfb85752a5fff) | llama : report compute graph reallocations during inference (#30329) | +| 2026-10-12T08:20:16Z | [2f160ba59ae7](https://github.com/ggml-org/llama.cpp/commit/2f160ba59ae7a84e014d7c0e67690d110058aa03) | ui: fix text attachment preview overflow (#29898) | +| 2026-10-12T08:06:27Z | [f9a95aeb2096](https://github.com/ggml-org/llama.cpp/commit/f9a95aeb2096d0c0218e0cd6e6d901cd37be798a) | sycl: guard DMMV reads at row tails (#29338) | +| 2026-10-12T06:00:26Z | [08ffba21e5c2](https://github.com/ggml-org/llama.cpp/commit/08ffba21e5c2f1728b6b405c05ff3913f65706d4) | vulkan: use ternary expressions to avoid switch lowering for CM2 quant block size (#30164) | +| 2026-10-12T05:50:12Z | [a05e58c981ea](https://github.com/ggml-org/llama.cpp/commit/a05e58c981ea1ec863b2f5b11bbde66f7bb7aac6) | ggml: Change default visibility of symbols to hidden (#30014) | +| 2026-10-12T04:51:24Z | [b2f036c0f138](https://github.com/ggml-org/llama.cpp/commit/b2f036c0f138414dedc987446f1d9d802f920275) | vulkan: fix buffer logging on 32-bit platforms after source split (#30326) | +| 2026-10-12T03:52:01Z | [e937b17a2df0](https://github.com/ggml-org/llama.cpp/commit/e937b17a2df081e9c7ae380f0dab4341c1585bce) | hexagon: optimize q2_k bpw and activation (#30035) | +| 2026-10-12T03:24:47Z | [b13a93a3d5fa](https://github.com/ggml-org/llama.cpp/commit/b13a93a3d5fa44b57899d86467a4de463e7415a7) | hexagon: add IM2COL_3D (#30305) | +| 2026-10-11T18:49:25Z | [f2cc7282ce00](https://github.com/ggml-org/llama.cpp/commit/f2cc7282ce0042641df55e0e563b75e824e2b647) | opencl: improve fa, allow dk512 for gemma-4, improve dk64 (#30266) | +| 2026-10-11T16:41:29Z | [c83f3058b6f8](https://github.com/ggml-org/llama.cpp/commit/c83f3058b6f876f2f7e6ccbada858b2446860c85) | opencl: fix image limit for q4_k dense bin kernels, q4_0 bcast and rms_norm (#30310) | +| 2026-10-11T14:43:35Z | [5c8854fd8831](https://github.com/ggml-org/llama.cpp/commit/5c8854fd88319125125dc4b836c98b1b215b0f23) | rpc : turn GGML_RPC_DEBUG into a verbosity level and add logs (#29544) | +| 2026-10-11T12:39:16Z | [a9d27ac693ff](https://github.com/ggml-org/llama.cpp/commit/a9d27ac693ff0a1d3cba449c912c2b891904a4c7) | model : support for Prism Bonsai 2 27B (#29600) | +| 2026-10-11T12:24:41Z | [1cf7767765b8](https://github.com/ggml-org/llama.cpp/commit/1cf7767765b872806e1bb74cfb55614f4334f02f) | cpu: fix AVX2 CPUs not using F16C when available (#30270) | +| 2026-10-11T12:02:57Z | [966baae76b57](https://github.com/ggml-org/llama.cpp/commit/966baae76b578d5d3dd4c179a75a35c80ff75577) | vulkan: handle mul_mat_id duplicates in the prepass rather than looping (#29998) | +| 2026-10-11T10:51:07Z | [62a6f74bab74](https://github.com/ggml-org/llama.cpp/commit/62a6f74bab748b1755f4cd8dfc0871caf865c6c8) | server: add component tests (#30312) | +| 2026-10-10T19:25:38Z | [23b0202a189c](https://github.com/ggml-org/llama.cpp/commit/23b0202a189c44a54625aadcb37a946dd1d6278d) | server: leave a busy slot untouched when a request pins it (#30295) | +| 2026-10-10T18:41:59Z | [69f201a2051e](https://github.com/ggml-org/llama.cpp/commit/69f201a2051ea9b9e9b50c3cc56afd9e2ae64414) | model : support MiniCPM-V 4.7 (#29416) | +| 2026-10-10T18:00:56Z | [abee0c8476b5](https://github.com/ggml-org/llama.cpp/commit/abee0c8476b585b0d081d580b5ce21d0addc22c4) | cmake(s390x): disable z17 target for unsupported compilers (#30297) | +| 2026-10-10T13:34:40Z | [aa94f2086147](https://github.com/ggml-org/llama.cpp/commit/aa94f2086147cd4bfbcff818ce998dffce5fcb39) | args: add LLAMA_ARG_SLOT_SAVE_PATH env for --slot-save-path (#30272) | +| 2026-10-10T09:22:38Z | [781dbc5ac989](https://github.com/ggml-org/llama.cpp/commit/781dbc5ac98921dbdb5e5b2ec5b7a50960e937d4) | spec: properly handle mtmd input for mtp (#30257) | +| 2026-10-10T09:22:12Z | [0fd868cbcadc](https://github.com/ggml-org/llama.cpp/commit/0fd868cbcadcbcd80373d1cb542ecbcfa115ca75) | mtmd: add build_inp_attn_mask (#30259) | +| 2026-10-10T06:15:42Z | [1623d8ce47bc](https://github.com/ggml-org/llama.cpp/commit/1623d8ce47bc0bee9757068780c23ca7abd45160) | cuda: always use MMVQ for MUL_MAT_ID on sm_60 (#27828) | +| 2026-10-10T06:14:51Z | [1bb2b9fcbe85](https://github.com/ggml-org/llama.cpp/commit/1bb2b9fcbe85c35c4e3b787e1c868ef05ca702f3) | CUDA/HIP: fix race in flash_attn_ext_f16_process_tile when nbatch_combine != DKQ/2 (#30103) | +| 2026-10-10T06:08:52Z | [2bbca8f202e7](https://github.com/ggml-org/llama.cpp/commit/2bbca8f202e76b25dac9116755bf1713a84e2753) | ggml-cpu: vectorize fp32 to fp16 conversion (#30157) | +| 2026-10-10T06:08:19Z | [404f557b5b14](https://github.com/ggml-org/llama.cpp/commit/404f557b5b143a448a304521ee1d4719ee40debe) | vulkan: use 4 rows for NVIDIA MUL_MAT_ID MMVQ (#29274) | +| 2026-10-10T06:07:52Z | [b797c82c7dbb](https://github.com/ggml-org/llama.cpp/commit/b797c82c7dbb2c5bbba2db2efe8febc65bc77857) | ggml: fix s390x all cpu build (#30140) | +| 2026-10-10T04:02:11Z | [f2918cabbffe](https://github.com/ggml-org/llama.cpp/commit/f2918cabbffe8abf8e2a90c1c089085fa116c2cf) | opencl: add bin kernels kernel_gemm_moe_q4_k_q8_1_dp4a_bin, kernel_gemm_moe_q6_k_q8_1_dp4a_bin (#30187) | +| 2026-10-10T02:56:23Z | [1e6f04a75e91](https://github.com/ggml-org/llama.cpp/commit/1e6f04a75e91da4bb66b5248f3fd4bdeff169d41) | sycl : accelerate MXFP4 MoE with arithmetic decoding and weight reordering (#29809) | +| 2026-10-09T22:07:44Z | [10a60cf30356](https://github.com/ggml-org/llama.cpp/commit/10a60cf303566e10d6a7a2774c17d2085503d87b) | vendor: apply deep nested json patch from upstream (#30253) | +| 2026-10-09T17:59:50Z | [79e2e74eb110](https://github.com/ggml-org/llama.cpp/commit/79e2e74eb11022c1ba2e438df7f0ca2d4c10f8b6) | CUDA: fix round issue, under MSVC the CPU and GPU agree (#30229) | +| 2026-10-09T17:43:05Z | [8e2d31e0eb65](https://github.com/ggml-org/llama.cpp/commit/8e2d31e0eb658d0382d3106a61369dff81f0c080) | graph : reorder get_rows for embeddings (#30160) | +| 2026-10-09T17:28:54Z | [baef3ed9a1e8](https://github.com/ggml-org/llama.cpp/commit/baef3ed9a1e81c4b620f6923857b1c080bffec5b) | ui: Models Manager Follow-up Improvements (#30228) | +| 2026-10-09T17:14:30Z | [f39148a953e5](https://github.com/ggml-org/llama.cpp/commit/f39148a953e52d6d14e92b73187e9883544dce49) | llama-bench: respect -fitc if bigger than required benchmark size (#28331) | +| 2026-10-09T16:23:28Z | [50e3e3e480c8](https://github.com/ggml-org/llama.cpp/commit/50e3e3e480c80b9ee0ea067e475602d540dc62c8) | CUDA: Remove redundant CUDA copies after SSM_SCAN (#29807) | +| 2026-10-09T16:19:20Z | [64df9183f5ca](https://github.com/ggml-org/llama.cpp/commit/64df9183f5ca178c049a392f35e795d8e97c97b3) | opencl: fix kernel compilation for a6x GPUs (#30176) | +| 2026-10-09T15:26:56Z | [6184e92c57dc](https://github.com/ggml-org/llama.cpp/commit/6184e92c57dcd34de8a3e381d7641a5e75250d5f) | model : use exact GELU for ModernBERT encoders (#30108) | +| 2026-10-09T15:06:22Z | [8b543610254a](https://github.com/ggml-org/llama.cpp/commit/8b543610254aafe121942eaf79a23c3847177270) | chat : refactor API (#30210) | +| 2026-10-09T14:20:25Z | [a518119d30ca](https://github.com/ggml-org/llama.cpp/commit/a518119d30cade6260f7494120863428a3fe8ee5) | llama: keep the backend sampling graph static across ubatches (#30223) | +| 2026-10-09T13:57:33Z | [8ae386707bed](https://github.com/ggml-org/llama.cpp/commit/8ae386707bed05f02354dbfc6fa5ee0cf58e5f0f) | ggml: fix OOB write in ggml_acc with negative offset (#30135) | +| 2026-10-09T13:01:04Z | [e60eff95fda7](https://github.com/ggml-org/llama.cpp/commit/e60eff95fda7b6e46bf402a8e9f1e86d88ab29c8) | meta : handle host views (#30217) | +| 2026-10-09T13:00:37Z | [ba6439a6b595](https://github.com/ggml-org/llama.cpp/commit/ba6439a6b595224c480d71572c0e4ac91d3e6afd) | webgpu: use 2D workgroup dispatch for all the ops which use 1D dispatch (e.g., rms_norm) (#30219) | +| 2026-10-09T13:00:14Z | [5e4878e9787f](https://github.com/ggml-org/llama.cpp/commit/5e4878e9787fff9bcc5c12478c47618b73268610) | vulkan: fix rms_norm workgroup count overflow (#30145) | +| 2026-10-09T11:54:58Z | [609290be6b15](https://github.com/ggml-org/llama.cpp/commit/609290be6b15db02f9d73443435403cbff6e7802) | convert : support compressed-tensor mixed-precision NVFP4 checkpoint (#28636) | +| 2026-10-09T10:51:24Z | [86a283532072](https://github.com/ggml-org/llama.cpp/commit/86a283532072722c5f3363d37d59a874d09fa99b) | musa: drop mp_21 from the default architectures (#30203) | +| 2026-10-09T10:27:32Z | [e94acad853c0](https://github.com/ggml-org/llama.cpp/commit/e94acad853c0d11a3b47974e3167ec12f263d86a) | ci: fix Models Backend webgpu by supporting GGML_OP_DUP (#30216) | +| 2026-10-09T09:12:24Z | [5e1d74043eb8](https://github.com/ggml-org/llama.cpp/commit/5e1d74043eb84f5f82471a1c5d4c8171a4c0fcba) | ci : set run-name for publish release (#30214) | +| 2026-10-09T08:40:03Z | [b42b7e6d3059](https://github.com/ggml-org/llama.cpp/commit/b42b7e6d3059503dd4bed6ca5dcf342bb6379f67) | server: use port 9931 by default (#30159) | +| 2026-10-09T08:34:45Z | [b013e56a7147](https://github.com/ggml-org/llama.cpp/commit/b013e56a7147dbff5ec03175828442a94086507c) | ui : add the models manager (#29583) | +| 2026-10-09T08:29:22Z | [2c564f43dfdb](https://github.com/ggml-org/llama.cpp/commit/2c564f43dfdb0565745dc71cc7748d2a1305246a) | ci: fix HIP quality check by ignoring the 320/256 FA kernel spill (#30212) | +| 2026-10-09T08:15:32Z | [1f8fa52318b5](https://github.com/ggml-org/llama.cpp/commit/1f8fa52318b594b373e7447a3c2bb36cdba9515f) | metal: add the 128/96 flash attention kernels, accept every compiled pair (#30209) | +| 2026-10-09T06:32:52Z | [8a1a9b512612](https://github.com/ggml-org/llama.cpp/commit/8a1a9b5126126e5228b95fa909d4b08fac65e8b3) | CUDA: pass src1 precision to host MMQ config helpers (#30168) | +| 2026-10-09T06:04:09Z | [d4d82d67f48b](https://github.com/ggml-org/llama.cpp/commit/d4d82d67f48bb8f51e9a3518063e49d9ee54f58b) | hexagon: fix IM2COL patch-embed DMA ring overflow (#30189) | +| 2026-10-09T02:19:32Z | [3d65c90d04d3](https://github.com/ggml-org/llama.cpp/commit/3d65c90d04d337e88f2b1f7f0061f40a5324e662) | sycl : Q5_K reorder-layout MMVQ and fused GLU (#29375) | +| 2026-10-08T19:56:54Z | [de7fa0a3c6a2](https://github.com/ggml-org/llama.cpp/commit/de7fa0a3c6a2e1b4cd9f22eb8d6bf5b12dbdb63b) | Musa FWHT fix (#30167) | +| 2026-10-08T16:34:27Z | [71ad0590f480](https://github.com/ggml-org/llama.cpp/commit/71ad0590f4808b6202f9213d166913858c73b1bc) | CUDA: improve top-k algorithm selection (#28713) | +| 2026-10-08T15:42:28Z | [a11f57ba9379](https://github.com/ggml-org/llama.cpp/commit/a11f57ba93797579a5d1855ee216a31f10242676) | model : fix DFlash output head sharing (#30111) | +| 2026-10-08T14:41:49Z | [fc9ce6b9d52a](https://github.com/ggml-org/llama.cpp/commit/fc9ce6b9d52a8504edcb262abc92737c2289f96c) | CUDA: fix MMQ out-of-bounds reads (#29953) | +| 2026-10-08T13:36:53Z | [c35b66744f13](https://github.com/ggml-org/llama.cpp/commit/c35b66744f13cb0dcc476af063e112122eee9355) | CUDA : looped PAD kernel for more than 65535 rows or slices (#30147) | +| 2026-10-08T13:29:34Z | [1167d3f42c2b](https://github.com/ggml-org/llama.cpp/commit/1167d3f42c2b4dc5469bf4e696cb8c678ca79110) | CUDA: fix CCCL version guard breaking on major version rollover (#29453) | +| 2026-10-08T13:08:22Z | [4f92965a7bfa](https://github.com/ggml-org/llama.cpp/commit/4f92965a7bfa9e8eb6519908ff962e23c2cb7b93) | ui: apply ui_settings on first visit in router mode (#29668) | +| 2026-10-08T10:20:49Z | [c811cb8f0ac9](https://github.com/ggml-org/llama.cpp/commit/c811cb8f0ac91b8ac72a32f970bdd45037f20da7) | llama: support MoE cache over multiple GPUs (#30112) | +| 2026-10-08T10:18:20Z | [033df86b69ec](https://github.com/ggml-org/llama.cpp/commit/033df86b69ec1a333eb241f0c16325a4d43dcff5) | server : preserve context checkpoints across slot save/restore (#26004) | +| 2026-10-08T10:14:35Z | [ff5888f999f2](https://github.com/ggml-org/llama.cpp/commit/ff5888f999f24e2f9eaf6537b4eb6b85fd559188) | vulkan : fix TOP_K for +inf/NaN inputs and k = 1 on negative values (#30107) | +| 2026-10-08T09:36:20Z | [dac308739429](https://github.com/ggml-org/llama.cpp/commit/dac308739429d60ccf99c46ecc1fbb1dff20ca77) | vulkan: extend sparse FA support to coopmat2 (#30003) | +| 2026-10-08T08:57:47Z | [03aa006acb54](https://github.com/ggml-org/llama.cpp/commit/03aa006acb547549162a00dddeab3d3b38ebf7b2) | vendor : update cpp-httplib to 0.60.1 (#30134) | +| 2026-10-08T07:21:42Z | [08246a28f600](https://github.com/ggml-org/llama.cpp/commit/08246a28f6000100433d297c4e037c02e9d2d464) | cuda : support arbitrary striding for unary ops on f16, f32, and bf16 (#29781) | +| 2026-10-08T06:50:22Z | [46baf1f1fec5](https://github.com/ggml-org/llama.cpp/commit/46baf1f1fec5a06d1e52122a9207ca978b720f95) | sycl: FWHT optimizations (#29605) | +| 2026-10-08T06:48:06Z | [097f5b5332f4](https://github.com/ggml-org/llama.cpp/commit/097f5b5332f46559f1ee11d9d64e48a5065b2989) | hex-mmadd: do not assume aligned read/write when bias-add is fused (#30133) | +| 2026-10-08T06:46:38Z | [d8880160413f](https://github.com/ggml-org/llama.cpp/commit/d8880160413fc77f63d6a73a5b1ac21ac65e36e1) | cuda : Use byte strides for roll to allow non-contiguous ROLL operations (#29547) | +| 2026-10-08T06:46:21Z | [fda186661304](https://github.com/ggml-org/llama.cpp/commit/fda186661304735bb9027abd472c1403a9902081) | CUDA: fix norm family kernels when ne[2]/ne[3] exceed grid dim limits (#28175) | +| 2026-10-08T06:45:21Z | [ff30363a0e3e](https://github.com/ggml-org/llama.cpp/commit/ff30363a0e3e2630828309ef5a37da5d1d40396c) | sycl: fuse the delta-net alpha gate (add + unary + mul) (#29687) | +| 2026-10-08T06:30:00Z | [000bee54a544](https://github.com/ggml-org/llama.cpp/commit/000bee54a544070356b44d68af299b973d391d26) | sycl: stage bulk uploads (model loading) through a pinned ring buffer (#29608) | +| 2026-10-08T06:29:20Z | [37ac63456643](https://github.com/ggml-org/llama.cpp/commit/37ac634566439e680959b90e1c960714ca6b8b92) | model : support classifier_activation for rerankers (#29692) | +| 2026-10-08T06:07:34Z | [24e41838e0c8](https://github.com/ggml-org/llama.cpp/commit/24e41838e0c834f67db214e6d280af51f266056e) | ggml-cuda: assign four GDN state columns per warp (#30087) | +| 2026-10-08T05:41:13Z | [847f447c310a](https://github.com/ggml-org/llama.cpp/commit/847f447c310a3784d623a953e6f0bb07f04c0f27) | sycl: add grouped MoE XMX GEMM (#29245) | +| 2026-10-08T05:40:01Z | [75118a3a5925](https://github.com/ggml-org/llama.cpp/commit/75118a3a5925d85e1850db67e87e447fa5890a47) | convert : support Qwen3.5 embedding models (#27920) | +| 2026-10-08T05:39:25Z | [9b4ed0ca572b](https://github.com/ggml-org/llama.cpp/commit/9b4ed0ca572be213f4440a490f341f810f7aa2cf) | sycl: remove duplicate block-size defines from op headers (#29507) | +| 2026-10-08T01:30:06Z | [9c2e0e491a82](https://github.com/ggml-org/llama.cpp/commit/9c2e0e491a822adae1f0b1c831adb4160057d24f) | hexagon: enable alloc_buffer_n (#30126) | +| 2026-10-08T00:13:21Z | [06cad0b9e773](https://github.com/ggml-org/llama.cpp/commit/06cad0b9e77315bd2930bd4f70a6d7b37b2a01c1) | hexagon: Q6_K weight dequant speedup (#30121) | +| 2026-10-08T00:07:49Z | [a657f7e981ff](https://github.com/ggml-org/llama.cpp/commit/a657f7e981ff8764d2ccce1e74ec3c7e9bf2cfa2) | model : add LiquidAI/d1-omni-600M decision model (#30114) | +| 2026-10-08T00:04:45Z | [aa5e0092fdb8](https://github.com/ggml-org/llama.cpp/commit/aa5e0092fdb8980b9e89498dfb73049b4fe204c2) | hexagon: support tiled Q4_K and Q6_K GET_ROWS (#30115) | +| 2026-10-07T23:57:09Z | [70815103c8b2](https://github.com/ggml-org/llama.cpp/commit/70815103c8b251bdf5abba4eca12749eab1de686) | hexagon: improved GELU accuracy (#30104) | +| 2026-10-07T20:48:06Z | [bd4eeaa04700](https://github.com/ggml-org/llama.cpp/commit/bd4eeaa047006cb1fe71999fbd11134b5836e167) | chat: fix jinja parser for TranslateGemma (#30096) | +| 2026-10-07T20:37:51Z | [5de733437bc5](https://github.com/ggml-org/llama.cpp/commit/5de733437bc5f6d6b2714b39c4023fd3d3b16698) | chat : name tool and argument parser rules by index (#30088) | +| 2026-10-07T20:04:39Z | [88dcc460d628](https://github.com/ggml-org/llama.cpp/commit/88dcc460d628698bb8305b98c200c34f1edfdc04) | model : add LiquidAI/d1-3B decision model (#30110) | +| 2026-10-07T18:56:18Z | [b86d2f07542b](https://github.com/ggml-org/llama.cpp/commit/b86d2f07542b29ab099aed34fd6b6d1b2fd4b81c) | cuda: FWHT kernels for block widths above 512 (#29100) | +| 2026-10-07T18:07:50Z | [50a6c5cf7c09](https://github.com/ggml-org/llama.cpp/commit/50a6c5cf7c09ea5ea9c1937e4895ce88331c2869) | mtmd: add cohere2 vision support (#30062) | +| 2026-10-07T18:07:45Z | [d6cf9acb25e6](https://github.com/ggml-org/llama.cpp/commit/d6cf9acb25e6c657d6c6a4645ab7b69fce119995) | llama : add a GPU cache for MoE experts kept in host memory (#29887) | +| 2026-10-07T17:53:43Z | [42c787e8c191](https://github.com/ggml-org/llama.cpp/commit/42c787e8c191d49c01c757f4b7029d69ec0bf2c8) | cuda: update uncoalesced memory reads in pool2d (#29425) | +| 2026-10-07T16:49:17Z | [18b5f8b1862e](https://github.com/ggml-org/llama.cpp/commit/18b5f8b1862ebfe0f1c33d2355b81a54d2fec867) | server : accumulate generated text and tokens as parse input (#29876) | +| 2026-10-07T14:30:00Z | [448147d42a71](https://github.com/ggml-org/llama.cpp/commit/448147d42a71d0147c6dc844f99f9ffe7419183a) | llama: share the nextn tensor flags between models (#30097) | +| 2026-10-07T13:49:37Z | [988190680d5a](https://github.com/ggml-org/llama.cpp/commit/988190680d5a89fce97de3c20df2c2813731fd61) | metal : few-row MMA mat-mul for the remaining src0 types (#30065) | +| 2026-10-07T13:41:50Z | [7e8324f5feba](https://github.com/ggml-org/llama.cpp/commit/7e8324f5feba1d8be3f966e1791e84107e40cdd7) | metal : fix MUL_MAT+ADD fusion when the residual is itself a MUL_MAT (#30100) | +| 2026-10-07T11:16:53Z | [b9acf138a1e2](https://github.com/ggml-org/llama.cpp/commit/b9acf138a1e28ce1fc23b5a4fc4b12444b50f7ea) | feat: add GLM5Next MTP, optimize (#29928) | +| 2026-10-07T10:57:48Z | [48499d2e1c86](https://github.com/ggml-org/llama.cpp/commit/48499d2e1c86c1d5fe7a05f8bf083156e7069cc0) | qwen3tts : guard speaker_encoder_config patch for CustomVoice variant (#29179) | +| 2026-10-07T10:34:18Z | [d0b490f25ede](https://github.com/ggml-org/llama.cpp/commit/d0b490f25edec147b4dcd69cce31c7d1099dff1d) | sampling : use greedy selection for eligible temperature-zero chains (#29797) | +| 2026-10-07T09:40:35Z | [42b021b4dc42](https://github.com/ggml-org/llama.cpp/commit/42b021b4dc42be573f1e1463528532fc8294c650) | vocab : add plamo fim tokens (#30090) | +| 2026-10-07T09:34:16Z | [7481354a1747](https://github.com/ggml-org/llama.cpp/commit/7481354a174714a3447ea0f8723c1dd1b3cbf8e2) | convert : fix token configuration for PLaMo-3 (#29843) | +| 2026-10-07T09:22:56Z | [ad2156533102](https://github.com/ggml-org/llama.cpp/commit/ad2156533102a0d3c4e5fbdf422dc25fba4d03ba) | musa: use the tile lightning indexer kernel (#30080) | +| 2026-10-07T09:18:33Z | [b7dafa01e5f3](https://github.com/ggml-org/llama.cpp/commit/b7dafa01e5f375c3010fb24b61a67329f957426a) | vendor : update cpp-httplib to 0.60.0 (#30081) | +| 2026-10-07T08:58:22Z | [26908739bc8a](https://github.com/ggml-org/llama.cpp/commit/26908739bc8ab9c5ccacbde5dc9c0b3609079e8f) | imatrix : include clocale for std::setlocale (#30079) | +| 2026-10-07T07:56:53Z | [36a73916ee0c](https://github.com/ggml-org/llama.cpp/commit/36a73916ee0cb3b457f356066afabd47cce68884) | ggml-webgpu: fix flash_attn supports_op check for overlapping KV (#28205) | +| 2026-10-07T07:44:10Z | [fa3c2fab3617](https://github.com/ggml-org/llama.cpp/commit/fa3c2fab361772f31116f2861a3c3583556a6fbe) | tests : retain the anchor when testing recurrent rollback (#29923) | +| 2026-10-07T07:24:43Z | [005a1e127a84](https://github.com/ggml-org/llama.cpp/commit/005a1e127a84cc75bb66be11b43e4f0773564e53) | [SYCL] fix the issue in mixed different model GPUs in FA (#29071) | +| 2026-10-07T07:24:07Z | [d2a79e604649](https://github.com/ggml-org/llama.cpp/commit/d2a79e60464903f9832fbecdba48bd4cc6c47e75) | sycl: accelerate GLM MLA prefill with MKL flash attention (#29171) | +| 2026-10-07T07:23:28Z | [5e5b628eb551](https://github.com/ggml-org/llama.cpp/commit/5e5b628eb5515d50de5c7f98a01937fc25b844b9) | sycl : fattn_kv_buffers cleanup (#27689) | +| 2026-10-07T06:20:04Z | [4d756bc72bf0](https://github.com/ggml-org/llama.cpp/commit/4d756bc72bf00a4aacf410ae15a2d315f3db400d) | vulkan: fix amd iGPU slow checkpoint read (#30049) | +| 2026-10-07T05:28:23Z | [78651c410dd8](https://github.com/ggml-org/llama.cpp/commit/78651c410dd8d97e3e22e533e0e7117889e3863a) | sycl: add IQ3_S multi-column MMVQ (#29500) | +| 2026-10-07T04:29:30Z | [f498f864fbc0](https://github.com/ggml-org/llama.cpp/commit/f498f864fbc0472004ee1c3616c1188c68eb157f) | ggml-webgpu: no dawn native features on wasi (#27069) | +| 2026-10-06T22:24:17Z | [c479922ac520](https://github.com/ggml-org/llama.cpp/commit/c479922ac520a08969b4c1dc154d7bbb3c386d85) | hexagon: CPY/CONCAT/CONT/DUP overhaul to use DMA/HVX for all cases (#30067) | diff --git a/lib/axes.py b/lib/axes.py index fa66f9d..57ebaed 100644 --- a/lib/axes.py +++ b/lib/axes.py @@ -113,6 +113,38 @@ "why": "логический батч: осмыслен только больше ubatch; в новых " "сборках n_batch клампится в n_ubatch", }, + { + "key": "moe_cache", "flag": "--moe-cache-mib", "probe": "moe-cache", + "values": "int", "gain": 4, "stage": "server", + "why": "GPU-кэш CPU MoE-экспертов (upstream #29887, #30112): " + "обмен VRAM на меньший PCIe/CPU overhead; только для MoE с offload", + }, + { + "key": "threads_batch", "flag": "--threads-batch", "alias": ["-tb"], + "probe": "threads-batch", "values": "int", "gain": 3, + "why": "потоки префилла отдельно от потоков декодинга", + }, + { + "key": "cpu_ffn", "flag": "--n-cpu-ffn", "alias": ["-ncffn"], + "probe": "cpu-ffn", "values": "int", "gain": 4, "stage": "server", + "why": "offload dense FFN в RAM: явный список, только для плотных моделей", + }, + { + "key": "op_offload", "flag": "--op-offload", "alias": ["--no-op-offload"], + "probe": "op-offload", "values": "enum:on,off", "gain": 2, + "why": "операции над host-тензорами на GPU или CPU; полезно при CPU offload", + }, + { + "key": "repack", "flag": "--repack", "alias": ["--no-repack"], + "probe": "repack", "values": "enum:on,off", "gain": 2, + "why": "переупаковка CPU-весов; явный A/B, требует перезагрузки модели", + }, + { + "key": "backend_sampling", "flag": "--backend-sampling", "alias": ["-bs"], + "probe": "backend-sampling", "values": "enum:off,on", "gain": 2, + "stage": "server", + "why": "экспериментальный sampling на backend; только по явному запросу", + }, ] BY_KEY = {a["key"]: a for a in AXES} @@ -307,6 +339,12 @@ def _load_results() -> list[dict]: "threads": ("t", "threads"), "b": ("b", "batch-size"), "spec": ("spec-type",), + "moe_cache": ("moe-cache-mib",), + "cpu_ffn": ("n-cpu-ffn",), + "threads_batch": ("threads-batch",), + "op_offload": ("op-offload",), + "repack": ("repack",), + "backend_sampling": ("backend-sampling",), } @@ -314,6 +352,9 @@ def _axis_values(cfg: dict) -> dict: """Значения осей в прогоне — по одному на ось.""" out = {} for key, names in CONFIG_KEY.items(): + if key == "kv_cache_type" and any(n in cfg for n in names): + out[key] = json.dumps([cfg.get("cache-type-k"), cfg.get("cache-type-v")]) + continue val = next((str(cfg[n]) for n in names if n in cfg), None) if val is not None: out[key] = val @@ -369,7 +410,10 @@ def learn(min_pairs: int = 2) -> dict: vram = r.get("min_observed_free_mib") if tps is None and vram is None: continue - runs.append({"axes": _axis_values(cfg), + axis_names = {n for names in CONFIG_KEY.values() for n in names} + identity = {k: v for k, v in cfg.items() if k not in axis_names} + identity["binary_fingerprint"] = r.get("binary_fingerprint") + runs.append({"identity": identity, "axes": _axis_values(cfg), "tps": float(tps) if tps else None, "vram": float(vram) if vram else None}) @@ -378,6 +422,8 @@ def learn(min_pairs: int = 2) -> dict: tp, vp, vals = [], [], set() for i, a in enumerate(runs): for b in runs[i + 1:]: + if a["identity"] != b["identity"]: + continue diff = [k for k in set(a["axes"]) | set(b["axes"]) if a["axes"].get(k) != b["axes"].get(k)] if diff != [key]: diff --git a/lib/budget.py b/lib/budget.py index 8375fe1..2d91250 100644 --- a/lib/budget.py +++ b/lib/budget.py @@ -69,11 +69,12 @@ class Estimate: model: str = "" notes: list[str] = field(default_factory=list) measured_min_free_mib: int | None = None + moe_cache_gb: float = 0.0 def as_dict(self) -> dict: d = {k: v for k, v in self.__dict__.items()} d["total_gb"] = round(self.total_gb, 2) - for k in ("weights_gb", "kv_gb", "mmproj_gb", "compute_gb"): + for k in ("weights_gb", "kv_gb", "mmproj_gb", "moe_cache_gb", "compute_gb"): d[k] = round(d[k], 2) return d @@ -373,7 +374,11 @@ def estimate(pairs: dict[str, str], meta: ModelMeta | None, est.mmproj_gb = mmproj_meta.size_bytes / GIB est.compute_gb = compute_gb - est.total_gb = est.weights_gb + est.kv_gb + est.mmproj_gb + est.compute_gb + est.moe_cache_gb = max(0, _get_int(low, "moe-cache-mib", default=0)) / 1024.0 + if est.moe_cache_gb: + est.notes.append(f"MoE GPU cache: дополнительно до {est.moe_cache_gb:.2f} GiB; " + "при нескольких GPU бюджет разделяется между ними") + est.total_gb = est.weights_gb + est.kv_gb + est.mmproj_gb + est.compute_gb + est.moe_cache_gb est.notes.append( f"compute buffer {compute_gb:.2f} GiB — подогнанная константа, " f"а не расчёт (см. llamastery budget calibrate)") diff --git a/lib/launch.py b/lib/launch.py new file mode 100644 index 0000000..526991f --- /dev/null +++ b/lib/launch.py @@ -0,0 +1,128 @@ +"""Shared launch-option handling for the wizard and tuner (no shell execution).""" +import re +import shlex +from pathlib import Path + +from . import schema + +# Stable internal spellings used by budget/tuning code. +KEYS = { + "model": "model", "m": "model", "ctx-size": "c", "c": "c", + "batch-size": "b", "b": "b", "threads": "t", "t": "t", + "flash-attn": "fa", "fa": "fa", "override-tensor": "ot", "ot": "ot", + "ngl": "n-gpu-layers", "gpu-layers": "n-gpu-layers", + "ncmoe": "n-cpu-moe", "ncffn": "n-cpu-ffn", "ub": "ubatch-size", "tb": "threads-batch", + "ctk": "cache-type-k", "ctv": "cache-type-v", +} +CONTROL = {"host", "port", "alias", "api-key", "api-key-file", "models-dir", + "models-max", "models-preset", "models-autoload", "help", "version"} + + +def option_key(key, flags): + f = schema.resolve(flags, key) + canon = f.canonical.lstrip("-") if f else key.lstrip("-") + # Negative aliases are actions, not synonyms for the positive switch. + if f and key.lstrip("-").startswith("no-"): + canon = next((a.lstrip("-") for a in f.aliases if a.startswith("--no-")), + key.lstrip("-")) + return KEYS.get(canon, canon) + + +def normalize(pairs, flags): + out = {} + for k, v in pairs.items(): + key = option_key(k, flags) + if key in {"no-kv-unified", "no-mmproj-offload", "no-op-offload", "no-repack"}: + key = key.removeprefix("no-") + v = "true" if str(v).lower() in {"0", "false", "no", "off", "disabled"} else "false" + out[key] = v + return out + + +def effective_pairs(ini, name, flags=None): + flags = flags or {} + sec = ini.section(name) + if sec is None: + raise ValueError("Секция не найдена") + # version is INI format metadata, not llama-server --version. + defaults = {k: v for k, v in ini.globals().items() if k != "version"} + return {**normalize(defaults, flags), **normalize(sec.pairs(), flags)} + + +def parse_cli(text, flags): + """Parse server flags; reject unknown/control options rather than lose them. + + Values remain single argv entries, including spaces, equals and negatives. + This intentionally accepts flags only, not an executable or shell command. + """ + tokens = shlex.split(text) + out = {} + i = 0 + while i < len(tokens): + token = tokens[i] + name, eq, value = token.partition("=") + f = schema.resolve(flags, name) if name.startswith("-") else None + if f is None: + raise ValueError(f"неизвестный флаг выбранной сборки: {name}") + key = option_key(name, flags) + if key in CONTROL or key in {"model", "hf-repo", "hf-file", "model-url"}: + raise ValueError(f"{name}: путь к модели и управление сервером задаются отдельно") + if f.kind == "flag": + if not eq: + value = "true" + if value.lower() not in {"true", "false", "1", "0", "yes", "no", "on", "off", "enabled", "disabled"}: + raise ValueError(f"{name}: ожидается булево значение") + elif not eq: + i += 1 + if i == len(tokens) or (tokens[i].startswith("-") and + not re.fullmatch(r"-\d+(?:\.\d+)?", tokens[i])): + raise ValueError(f"{name}: не задано значение") + value = tokens[i] + if not value and f.kind != "flag": + raise ValueError(f"{name}: пустое значение") + if f.kind in {"int", "float"} and not (key == "n-gpu-layers" and value in {"auto", "all"}): + try: + float(value) # N in --help is also used for floating-point options + except ValueError: + raise ValueError(f"{name}: ожидается число") from None + # The INI parser treats whitespace + #/; as a comment. Do not silently + # truncate an arbitrary CLI value when persisting it. + if "\n" in value or "\r" in value or re.search(r"\s[;#]", value): + raise ValueError(f"{name}: значение нельзя без потерь записать в INI") + if key in out: + raise ValueError(f"{name}: повторный флаг; INI хранит одно значение на ключ") + if f.kind == "path": + value = str(Path(value).expanduser().resolve()) + out[key] = value + i += 1 + return out + + +def resolve_option(flags, key): + f = schema.resolve(flags, key) + if f is None: + f = next((schema.resolve(flags, alias) for alias, internal in KEYS.items() + if internal == key and schema.resolve(flags, alias)), None) + return f + + +def flag_argv(key, value, flags): + """Serialize one schema-known option, preserving negative switches.""" + f = resolve_option(flags, key) + if f is None: + raise ValueError(f"неизвестный флаг выбранной сборки: {key}") + name = f.canonical + if key.lstrip("-").startswith("no-"): + name = "--" + key.lstrip("-") + value = str(value) + if f.kind != "flag": + return [name, value] + if value.lower() in {"0", "false", "no", "off", "disabled"}: + if name.startswith("--no-"): + return [f.canonical] if not f.canonical.startswith("--no-") else [] + negative = "--no-" + name.lstrip("-") + if schema.resolve(flags, negative): + return [negative] + # A false opt-in switch must not accidentally become true. + return [] + return [name] diff --git a/lib/measure.py b/lib/measure.py index 4ddf262..fbea295 100644 --- a/lib/measure.py +++ b/lib/measure.py @@ -19,7 +19,7 @@ # динамику генерации (доля токенов в мыслях), DRY — штраф повторов, сэмплинг — # форму распределения. Без них в подписи замеры двух пресетов, отличающихся # только reasoning-budget, склеивались бы в один. -SIGNIFICANT = ("c", "n-cpu-moe", "n-gpu-layers", "ngl", "b", "batch-size", +SIGNIFICANT = ("moe-cache-mib", "n-cpu-ffn", "op-offload", "repack", "backend-sampling", "c", "n-cpu-moe", "n-gpu-layers", "ngl", "b", "batch-size", "ubatch-size", "ub", "t", "threads", "threads-batch", "tb", "parallel", "np", "fa", "flash-attn", "cache-type-k", "ctk", "cache-type-v", "ctv", "kv-unified", "kvu", "spec-type", @@ -65,7 +65,8 @@ _TRUE = {"1", "true", "on", "yes", "y"} _FALSE = {"0", "false", "off", "no", "n"} _FLAGGY = {"fa", "flash-attn", "kv-unified", "kvu", "jinja", "cont-batching", - "cache-prompt", "context-shift", "mmproj-offload", "fit"} + "cache-prompt", "context-shift", "mmproj-offload", "fit", + "op-offload", "repack", "backend-sampling"} def _norm_value(key: str, value) -> str: diff --git a/lib/schema.py b/lib/schema.py index ed05279..d1a66dc 100644 --- a/lib/schema.py +++ b/lib/schema.py @@ -14,6 +14,7 @@ """ import json +import os import re import subprocess import time @@ -28,6 +29,8 @@ r"^(?:" r"\{[^}]*\}|\[[^\]]*\]|\([^)]*\)|<[^>]*>|[A-Z][A-Z0-9_]*|[A-Z0-9]+|lo-hi|[-0-9.]+" r"|[A-Za-z0-9_.\-]+,[A-Za-z0-9_.\-]+(?:,[A-Za-z0-9_.\-]*)*" + r"|[A-Z][A-Z0-9_]*(?:[=:][A-Z][A-Z0-9_]*)+" + r"|<[^>]+>(?:[=:]<[^>]+>)+" r")$" ) _ENV_RE = re.compile(r"\(env:\s*([A-Z0-9_]+)\s*\)") @@ -121,8 +124,11 @@ def _split_line(line: str) -> tuple[list[str], str | None, str]: value_hint, desc = None, "" if idx < len(tokens): tok = tokens[idx] - head = " ".join(forms) - if _HINT_RE.match(tok): + # Two or more spaces begin the description column. Otherwise prose + # starting with "KV"/"HTTP" looks like an uppercase value placeholder. + end = line.find(forms[-1]) + len(forms[-1]) + gap = re.match(r"\s*", line[end:]).group() + if _HINT_RE.match(tok) and len(gap) < 2: value_hint = tok m = re.search(re.escape(tok) + r"\s{2,}(.*)$", line) desc = m.group(1).strip() if m else "" @@ -157,7 +163,7 @@ def _classify(value_hint: str | None, desc: str) -> tuple[str, list[str]]: return "string", [] if re.fullmatch(r"[A-Za-z0-9_.\-]+", value_hint): return "string", [] - return "flag", [] + return "string", [] def parse_help(text: str) -> dict[str, Flag]: @@ -193,9 +199,9 @@ def parse_help(text: str) -> dict[str, Flag]: shorts = [f for f in forms if not f.startswith("--")] longs = [f for f in forms if f.startswith("--")] if longs: - canonical, short, alias = longs[0], (shorts[0] if shorts else None), longs[1:] + canonical, short, alias = longs[0], (shorts[0] if shorts else None), longs[1:] + shorts[1:] else: - canonical, short, alias = shorts[0], shorts[0], [] + canonical, short, alias = shorts[0], shorts[0], shorts[1:] env = None em = _ENV_RE.search(desc) @@ -219,8 +225,12 @@ def parse_help(text: str) -> dict[str, Flag]: def run_help(binary: str | Path, timeout: int = 60) -> str: + env = dict(os.environ) + bindir = str(Path(binary).resolve().parent) + env["LD_LIBRARY_PATH"] = bindir + (":" + env["LD_LIBRARY_PATH"] + if env.get("LD_LIBRARY_PATH") else "") p = subprocess.run([str(binary), "--help"], capture_output=True, - text=True, timeout=timeout) + text=True, timeout=timeout, env=env) return (p.stdout or "") + (p.stderr or "") @@ -241,13 +251,14 @@ def load(binary: str | Path | None, use_cache: bool = True, st = binary.stat() mtime = st.st_mtime meta = {"binary": str(binary), "mtime": mtime, - "size": st.st_size} + "size": st.st_size, "parser_version": 2} cached = paths.schema_cache(binary) if use_cache and cached.exists() and not refresh: try: blob = json.loads(cached.read_text(encoding="utf-8")) - if blob.get("meta", {}).get("mtime") == mtime: + if (blob.get("meta", {}).get("mtime") == mtime + and blob.get("meta", {}).get("parser_version") == 2): return ({k: Flag(**v) for k, v in blob["flags"].items()}, blob["meta"]) except (json.JSONDecodeError, TypeError, ValueError): diff --git a/lib/wizard.py b/lib/wizard.py index 4fb284d..92a4d39 100644 --- a/lib/wizard.py +++ b/lib/wizard.py @@ -17,13 +17,14 @@ import ast import re +import shlex import subprocess import sys from dataclasses import dataclass from functools import lru_cache from pathlib import Path -from . import builds, budget, gguf, measure, paths, presets, server, swap, tui, vram +from . import builds, budget, gguf, launch, measure, paths, presets, schema, server, swap, tui, vram from .i18n import t STAR = "★" @@ -377,7 +378,8 @@ def find_mmproj_sibling(names: list[str], current: str) -> str | None: # ключи, которые указывают на ФАЙЛЫ чужой модели: переносить их в новую # секцию нельзя, иначе validate поймает путь, а load — несовместимость _PATH_KEYS = ("model", "m", "hf-repo", "hf-file", "mmproj", "model-draft", - "mmproj-offload", "image-min-tokens") + "mmproj-offload", "image-min-tokens", "model-url", "hf-repo-draft", + "hf-file-draft", "chat-template-file", "lora", "lora-scaled") def _int(val) -> int: @@ -410,6 +412,7 @@ def pairs_for_custom_model(base: dict, path: str, meta=None, по метаданным: контекст — по обученному окну, n-cpu-moe — по числу слоёв и только для MoE. """ + base = launch.normalize(base, {}) low = {k.lower(): v for k, v in base.items()} out = {"model": path} if mmproj: @@ -423,6 +426,7 @@ def pairs_for_custom_model(base: dict, path: str, meta=None, out[k] = v if meta is None: return out + out.setdefault("c", str(min(meta.n_ctx_trained or 8192, 8192))) c = _int(out.get("c") or out.get("ctx-size")) if c and meta.n_ctx_trained and c > meta.n_ctx_trained: @@ -435,6 +439,13 @@ def pairs_for_custom_model(base: dict, path: str, meta=None, ncpu = _int(out.get("n-cpu-moe")) if ncpu and meta.n_layer and ncpu > meta.n_layer: out["n-cpu-moe"] = str(meta.n_layer) + if meta.is_moe: + out.pop("n-cpu-ffn", None) + else: + nffn = _int(out.get("n-cpu-ffn")) + if meta.n_layer and nffn > meta.n_layer: + out["n-cpu-ffn"] = str(meta.n_layer) + out.pop("moe-cache-mib", None) # драфт-головы из базы мы не перенесли, поэтому внешний MTP не запустится: # ускоритель оставляем тот, что работает на любой модели if "draft" in str(out.get("spec-type", "")) and not meta.n_layer_nextn: @@ -569,6 +580,10 @@ def measurement_of(pairs: dict, records: dict) -> dict | None: "runs": rec.get("runs", 0)} +def _effective_pairs(ini, name): + return launch.effective_pairs(ini, name) + + def _preset_options( ini, custom: bool = False ) -> tuple[list[tuple[str, str]], list[str], str | None]: @@ -604,7 +619,7 @@ def _preset_options( return opts, sections, default_name -def _custom_preset(ini, prefilled: str | None = None) -> str | None: +def _custom_preset(ini, prefilled: str | None = None, build: str | None = None) -> str | None: """Пункт «свой .gguf»: путь → чьи флаги → новая секция в models.ini. prefilled — путь, вставленный прямо в вопрос со списком пресетов: тогда @@ -627,8 +642,8 @@ def _custom_preset(ini, prefilled: str | None = None) -> str | None: if not raw: note(t('путь не задан — возвращаюсь к списку пресетов')) return None - path = Path(raw).expanduser() - if not path.exists(): + path = Path(raw.strip().strip("\"'")).expanduser().resolve() + if not path.is_file(): warn(t('нет файла: {0}', path)) return None try: @@ -638,24 +653,50 @@ def _custom_preset(ini, prefilled: str | None = None) -> str | None: return None note(t('на диске: {0}', meta.summary())) + binary, _ = builds.resolve_binary(build) + flags, _ = schema.load(binary) if binary else ({}, {}) opts, sections, default_name = _preset_options(ini) - if opts: - base = ask_pick(f"Вопрос {qnum()} · чьи флаги берём", opts, - sections.index(default_name) + 1 if default_name else 1, - sub="файловые ключи (model, mmproj, драфт) не копируются — " - "они указывают на чужой файл") - base_pairs = ini.section(base).pairs() - else: - warn(t('в ini нет ни одного пресета — беру только глобальные [*]')) - base_pairs = ini.globals() + clean = "Без копирования чужого пресета" + base = ask_pick(f"Вопрос {qnum()} · чьи флаги берём", + opts + [(clean, "только глобальные [*] и безопасный контекст")], + len(opts) + 1, + sub="копирование чужих настроек — только осознанно; " + "ниже можно добавить флаги этой модели") + base_pairs = (ini.section(base).pairs() if base != clean else {}) + base_pairs = launch.normalize(base_pairs, flags) mmproj = gguf.find_mmproj_near(path) if mmproj: note(t('рядом нашёлся mmproj: {0}', Path(mmproj).name)) + if not ask_yn("использовать этот mmproj?", + sub="соседний файл может быть от другой модели; Enter — без зрения"): + mmproj = None else: note(t('mmproj рядом не найден — зрения в этой секции не будет')) pairs = pairs_for_custom_model(base_pairs, str(path), meta, mmproj) + # Display inherited flags as well: the router and tuner both use [*]. + note("флаги новой модели (включая [*]):") + for k, v in {**{k: v for k, v in ini.globals().items() if k != "version"}, + **pairs}.items(): + note(f" {k} = {v}") + for _ in range(MAX_SUBSTEP): + text = ask_text(f"Вопрос {qnum()} · дополнительные флаги llama-server", "", + sub="например: --chat-template-file '/path/template.jinja' " + "--rope-scaling yarn; Enter — без изменений; " + "это НЕ параметры тюнера --extra") + try: + overrides = launch.parse_cli(text, flags) + except ValueError as exc: + warn(str(exc)) + continue + pairs.update(launch.normalize(overrides, flags)) + break + else: + return None + # Confirm the exact section, not just its key count. + for k, v in pairs.items(): + note(f" {k} = {v}") name = section_name_for(str(path), [n for n in ini.names() if n != "*"]) note("") note(t('новая секция [{0}]: {1} ключей, c={2}, n-cpu-moe={3}', name, len(pairs), pairs.get('c', '?'), pairs.get('n-cpu-moe', '-'))) @@ -672,7 +713,7 @@ def _custom_preset(ini, prefilled: str | None = None) -> str | None: # первая строка получает пояснение, откуда взялась секция sec.add(k, v, comment=(f"создано мастером из {path.name}\n" + (f"флаги скопированы из [{base}]" - if opts else "флаги — из [*]") + if base != clean else "без копирования пресета") ) if i == 0 else None) ini.save() note(f"записано: {ini.path}" @@ -760,28 +801,26 @@ def _tune_argv(build: str | None, preset: str, pairs: dict, if build: argv += ["--build", build] + pairs = launch.normalize(pairs, {}) cur = _int(pairs.get("c")) + extra = [] + if pairs.get("mmproj"): + extra.append("keep-mmproj") + if pairs.get("ot"): + extra.append("allow-ot") + if pairs.get("spec-type", "none") not in ("", "none"): + extra.append("with-spec") if shrink is not None: - # формат именно k=v: cmd_tune превращает «k=v» в «--k v», а - # отдельное значение без «=» стало бы флагом «--16384» - extra = [] if shrink.ctx and shrink.ctx != cur: extra.append(f"search-ctx={shrink.ctx}") if shrink.cpu_moe: - # верх серии — максимум между подобранным и ТЕКУЩИМ n-cpu-moe - # пресета (заведомо рабочая точка), а не контекстом: `c` к числу - # слоёв отношения не имеет cur_moe = _int(pairs.get("n-cpu-moe")) or 0 top = (max(shrink.cpu_moe + 1, min(shrink.n_layer - 1, cur_moe)) if shrink.n_layer else 0) extra.append(f"moe-values={_moe_series(shrink.cpu_moe, top)}") - if not extra: - return argv - return argv + ["--extra", *extra] - - if cur > TUNE_SEARCH_CTX: - return argv + ["--extra", f"search-ctx={TUNE_SEARCH_CTX}"] - return argv + elif cur > TUNE_SEARCH_CTX: + extra.append(f"search-ctx={TUNE_SEARCH_CTX}") + return argv + (["--extra", *extra] if extra else []) def _moe_series(start: int, top: int) -> str: @@ -903,13 +942,6 @@ def _run_tune(build: str | None, preset: str, pairs: dict) -> int: note(t('не запускаю — команды в плане остаются ручными')) return 1 - busy = [m["id"] for m in server.status().get("models", []) - if m.get("status") in ("loaded", "sleeping", "loading")] - if busy: - warn("в VRAM сидит: " + ", ".join(busy)) - if ask_yn("выгрузить перед автотюном?", - sub="иначе тюнеру не хватит памяти и прогоны упадут"): - _run_cli("runtime", "unload") argv = _tune_argv(build, preset, pairs, shrink) unknown = _tune_unknown_keys(argv) if unknown: @@ -918,12 +950,26 @@ def _run_tune(build: str | None, preset: str, pairs: dict) -> int: warn("тюнер не знает флагов: " + ", ".join(unknown)) note(t('похоже, тюнер и мастер разошлись во флагах — llamastery axes refresh')) return 1 + + busy = [m["id"] for m in server.status().get("models", []) + if m.get("status") in ("loaded", "sleeping", "loading")] + if busy: + warn("в VRAM сидит: " + ", ".join(busy)) + if ask_yn("выгрузить перед автотюном?", + sub="иначе тюнеру не хватит памяти и прогоны упадут"): + rc = _run_cli("runtime", "unload") + if rc: + warn("выгрузка не удалась — автотюн остановлен") + return rc + else: + note("автотюн отменён: модели остались в VRAM") + return 1 rc = _run_cli(*argv) if rc: warn(t('тюнер вернул код {0}', rc)) else: - note(t('пресет не изменён: разбор — в tune-results рядом с models.ini, запись — llamastery tune … --deep --apply')) - if shrink is not None and (shrink.ctx != _int(pairs.get("c")) + note('результаты подбора не записаны в пресет: разбор — в tune-results рядом с models.ini; запись — llamastery tune <секция> --extra deep apply') + if shrink is not None and ((shrink.ctx and shrink.ctx != _int(pairs.get("c"))) or shrink.cpu_moe): note(t('подбор шёл на c={0}, n-cpu-moe={1}: эти значения стоит записать в секцию, иначе load вернёт старое и упадёт по VRAM', shrink.ctx, shrink.cpu_moe)) return rc @@ -1122,6 +1168,8 @@ def _setup_flow(swap_url: str): from .inifile import IniFile try: ini = IniFile.load(str(paths.default_ini())) + except FileNotFoundError: + ini = IniFile(paths.default_ini(), "") except OSError as exc: warn(t('не читается {0}: {1}', paths.default_ini(), exc)) return 1 @@ -1163,7 +1211,7 @@ def s_preset(a: dict): if choice != CUSTOM_MODEL: return choice try: - name = _custom_preset(ini, pasted) + name = _custom_preset(ini, pasted, a.get("build")) except _GoBack: continue if name: @@ -1175,28 +1223,33 @@ def s_tune(a: dict): preset = a.get("preset") if not preset: return None - pairs = ini.section(preset).pairs() + pairs = _effective_pairs(ini, preset) if not ask_yn(f"Вопрос {qnum()} · прогнать автотюн этого пресета?", sub="долго (10–30 мин) и грузит GPU на 100% — " "только явным «д», Enter ничего не запустит"): return "не просил" # сам запуск — после плана: там человек один раз решает, можно ли # начинать, и к этому моменту известно про mmproj и ускорители - note(t('команда: llamastery {0}', ' '.join(_tune_argv(a.get('build'), preset, pairs)))) + note(t('команда: llamastery {0}', shlex.join(_tune_argv(a.get('build'), preset, pairs)))) note(t('запущу после плана — там же спрошу, можно ли начинать')) return "да" def s_ctx(a: dict): preset = a.get("preset") - cur = ini.section(preset).pairs().get("c", "?") if preset else "?" - return ask_text(f"Вопрос {qnum()} · контекст", str(cur), - sub="больше контекст = больше KV = больше VRAM") + cur = _effective_pairs(ini, preset).get("c", "8192") if preset else "8192" + for _ in range(MAX_SUBSTEP): + value = ask_text(f"Вопрос {qnum()} · контекст", str(cur), + sub="целое число 4096..262144; больше KV = больше VRAM") + if value.isdigit() and 4096 <= int(value) <= 262144: + return str(int(value)) + warn("контекст должен быть целым числом 4096..262144") + return BACK def s_vision(a: dict): preset = a.get("preset") if not preset: return None - low = {k.lower() for k in ini.section(preset).pairs()} + low = {k.lower() for k in _effective_pairs(ini, preset)} sections = [n for n in ini.names() if n != "*"] sibling = find_mmproj_sibling(sections, preset) if "mmproj" in low: @@ -1213,14 +1266,14 @@ def s_vision(a: dict): def s_ngram(a: dict): preset = a.get("preset") or "" - pairs = ini.section(preset).pairs() if preset else {} + pairs = _effective_pairs(ini, preset) if preset else {} return ask_yn(f"Вопрос {qnum()} · тестить с ngram (спекулятивный декодер)?", ngram_default(pairs), sub="×3–4 на повторяющемся тексте, но медленнее на уникальном") def s_mtp(a: dict): preset = a.get("preset") or "" - pairs = ini.section(preset).pairs() if preset else {} + pairs = _effective_pairs(ini, preset) if preset else {} return ask_yn(f"Вопрос {qnum()} · тестить с MTP (черновая голова)?", mtp_default(preset, pairs)) @@ -1246,8 +1299,19 @@ def s_mtp(a: dict): if res.get("vision") and res["vision"] not in ("включено", "текстовый"): preset = res["vision"] ctx = res.get("ctx") - pairs = ini.section(preset).pairs() + pairs = _effective_pairs(ini, preset) want_tune = res.get("tune") == "да" + updates = {} + if ctx and ctx != pairs.get("c"): + updates["c"] = ctx + if want_tune: + spec = ("draft-mtp" if res.get("mtp") else + "ngram-mod" if res.get("ngram") else "none") + if spec != pairs.get("spec-type", "none"): + updates["spec-type"] = spec + if res.get("mtp") and res.get("ngram"): + note("выбраны оба ускорителя: для этого прогона используем MTP") + pairs.update(updates) head("план", "выполняется по порядку, каждый шаг можно пропустить") steps = [f"validate {preset} --build {res['build']}", @@ -1255,7 +1319,7 @@ def s_mtp(a: dict): if want_tune: # раньше тюн стоял первым, а выполнялся бы после проверок — список # должен совпадать с тем, что реально происходит - steps.append(" ".join(_tune_argv(res["build"], preset, pairs))) + steps.append(shlex.join(_tune_argv(res["build"], preset, pairs))) steps += [f"load {preset} --build {res['build']}", f"measure --swap-url {swap_url} {preset}", f"probe --tokens 110000 --from-file <реальный-код> --record " @@ -1265,29 +1329,45 @@ def s_mtp(a: dict): print(f" {i}. llamastery {st}") if res.get("ngram") or res.get("mtp"): note(t('ускорители в тесте: ngram={0}, mtp={1} (флаги — в пресет перед load)', 'да' if res.get('ngram') else 'нет', 'да' if res.get('mtp') else 'нет')) - if ctx and ctx != str(pairs.get("c", "")): - warn(t('контекст {0} → {1}: сначала правка models.ini', pairs.get('c'), ctx)) + if updates: + note("после подтверждения запишу в пресет с резервной копией: " + + ", ".join(f"{k}={v}" for k, v in updates.items())) print() question = ("выполнить автотюн и первые два шага (validate + budget)?" if want_tune else - "выполнить первые два шага (validate + budget, безопасно)?") + "выполнить первые два шага (validate + budget)?") try: go = ask_yn(question, - sub="автотюн — надолго, GPU на 100%" if want_tune else "") + sub=("изменения выше будут записаны в models.ini с резервной копией. " + if updates else "") + + ("автотюн — надолго, GPU на 100%" if want_tune else "")) except _GoBack: # последний экран потока: «назад» здесь — это в меню note(t('ничего не выполнял')) return "menu" if go: + if updates: + presets.backup(ini.path) + sec = ini.section(preset) + for key, value in updates.items(): + # Remove all aliases/duplicates of this setting first, otherwise + # the old long spelling may override the new short one. + sec.entries = [e for e in sec.entries + if e.key is None or launch.option_key(e.key, {}) != key] + sec.add(key, value) + ini.save() + # Never spend 30 minutes after a failed preflight, nor report a failed + # tuner as success. Budget warnings are errors returned by the CLI too. + for command in (("validate", preset, "--build", res["build"]), + ("budget", preset, "--explain")): + rc = _run_cli(*command) + if rc: + warn(f"{command[0]} вернул код {rc} — дальнейшие шаги остановлены") + return rc if want_tune: - # тюнеру память нужнее, чем проверке: сначала validate и budget - # (быстро), и только потом прогон на 10–30 минут - _run_cli("validate", preset, "--build", res["build"]) - _run_cli("budget", preset, "--explain") - _run_tune(res["build"], preset, pairs) - else: - _run_cli("validate", preset, "--build", res["build"]) - _run_cli("budget", preset, "--explain") + rc = _run_tune(res["build"], preset, pairs) + if rc: + return rc print() note(t('готово. загрузка вручную: llamastery load {0} --build {1}', preset, res['build'])) return 0 diff --git a/tests/fixtures/upstream-2026-10-14-bench-help.txt b/tests/fixtures/upstream-2026-10-14-bench-help.txt new file mode 100644 index 0000000..9aa7fe5 --- /dev/null +++ b/tests/fixtures/upstream-2026-10-14-bench-help.txt @@ -0,0 +1,19 @@ +# Curated print_usage declarations from tools/llama-bench/llama-bench.cpp +# fcac19079f3f2985fe74ed845f0880e7e9a8030a. Only declarations actually +# present in upstream bench are listed here. +-fitt, --fit-target fit margin (default: off) +-fitc, --fit-ctx minimum fit context (default: 0) +-m, --model model +-p, --n-prompt prompt tokens +-n, --n-gen generated tokens +-d, --n-depth context depth +-b, --batch-size logical batch +-ub, --ubatch-size physical batch +-ctk, --cache-type-k K cache +-ctv, --cache-type-v V cache +-t, --threads threads +-ngl, --n-gpu-layers GPU layers +-ncmoe, --n-cpu-moe MoE in CPU +-fa, --flash-attn FA +-nopo, --no-op-offload <0|1> offload operations +--repack <0|1> repacking diff --git a/tests/fixtures/upstream-2026-10-14-server-help.txt b/tests/fixtures/upstream-2026-10-14-server-help.txt new file mode 100644 index 0000000..9f1a47e --- /dev/null +++ b/tests/fixtures/upstream-2026-10-14-server-help.txt @@ -0,0 +1,25 @@ +# Curated help declarations from ggml-org/llama.cpp common/arg.cpp +# fcac19079f3f2985fe74ed845f0880e7e9a8030a (2026-10-14 review). +# This is a test fixture, not the output of a locally built binary. +-m, --model FNAME model +-c, --ctx-size N context +-ngl, --gpu-layers, --n-gpu-layers N GPU layers +-ncmoe, --n-cpu-moe N MoE experts in CPU +--moe-cache-mib N GPU cache for CPU MoE experts (env: LLAMA_ARG_MOE_CACHE_MIB) +-ncffn, --n-cpu-ffn N dense FFN in CPU +-b, --batch-size N logical batch +-ub, --ubatch-size N physical batch +-t, --threads N decode threads +-tb, --threads-batch N prefill threads +-ctk, --cache-type-k TYPE K cache +-ctv, --cache-type-v TYPE V cache +-fa, --flash-attn [on|off|auto] flash attention +--op-offload, --no-op-offload offload host operations +--repack, -nr, --no-repack CPU weight repacking +-bs, --backend-sampling experimental backend sampling +-fit, --fit [on|off] fit to device memory +-kvu, --kv-unified, -no-kvu, --no-kv-unified KV sharing +-np, --parallel N slots +--jinja templates +--host HOST listen host +--port PORT listen port diff --git a/tests/run_tests.py b/tests/run_tests.py index b2c8b05..45eb6fa 100644 --- a/tests/run_tests.py +++ b/tests/run_tests.py @@ -486,6 +486,7 @@ def test_tuner_passthrough(): kinds = {"--spec-type": "string", "--model-draft": "string", "--fit": "enum", "--spec-ngram-mod-n-max": "int"} orig = mod._flag_kinds + mod._SCHEMA_CACHE["/bin/true"] = {} mod._flag_kinds = lambda binary: kinds opts = {"model": "/m.gguf", "c": "114688", "n-gpu-layers": "99", "n-cpu-moe": "24", "b": "2048", "ubatch-size": "1024", "t": "8", @@ -1376,7 +1377,7 @@ def test_tune_axes_skip_current_and_dedup() -> None: "текущее n-cpu-moe не проверяется заново", [c["moe"] for c in moe_axis]) fa_axis = [c for c in cands if c["_axis"] == "fa"] - check(fa_axis and all(c["fa"] != base["fa"] for c in fa_axis), + check(all(c["fa"] != base["fa"] for c in fa_axis), "текущее fa не проверяется заново", [c["fa"] for c in fa_axis]) ub_axis = [c for c in cands if c["_axis"] == "ubatch"] check(ub_axis and all(c["ubatch"] != base["ubatch"] for c in ub_axis), @@ -1686,7 +1687,7 @@ def test_wizard_custom_gguf_preset(tmp: Path) -> None: ini_path = tmp / "models.ini" ini_path.write_text(CUSTOM_INI, encoding="utf-8") ini = inifile.IniFile(ini_path, CUSTOM_INI) - answers = iter([str(model), "1", "y"]) # путь, чьи флаги, дописать + answers = iter([str(model), "1", "y", "", "y"]) # путь, чьи флаги, дописать orig_read = wizard._read wizard._read = lambda prompt: next(answers) try: @@ -1716,7 +1717,7 @@ def test_wizard_custom_gguf_preset(tmp: Path) -> None: # ── отказ не оставляет мусора ── ini2 = inifile.IniFile(ini_path, CUSTOM_INI) - answers2 = iter([str(model), "1", "n"]) + answers2 = iter([str(model), "1", "n", "", "n"]) wizard._read = lambda prompt: next(answers2) try: rc = wizard._custom_preset(ini2) @@ -2056,7 +2057,8 @@ def test_wizard_pasted_path_is_not_a_number(tmp: Path) -> None: # Ответы: сборка, вставленный путь, чьи флаги, дописать, тюн, контекст, # ngram, mtp, финал model = _write_fake_gguf(tmp / "Pasted Model.gguf") - env, calls = _wizard_env(tmp, ["1", str(model), "1", "y", "n", "", "n", + (tmp / "mmproj-Q8_0.gguf").write_bytes(b"GGUF" + b"\0" * 64) + env, calls = _wizard_env(tmp, ["1", str(model), "1", "y", "", "y", "n", "", "n", "n", "n"]) with env: rc = wizard._setup_flow("http://127.0.0.1:8087") @@ -2937,5 +2939,452 @@ def trap_keys(pairs): probe.close() + + +CUSTOM_LAUNCH_HELP = """ +-m, --model FNAME model path +-c, --ctx-size N context (env: LLAMA_ARG_CTX_SIZE) +-C, --cpu-mask MASK CPU mask +-ngl, --n-gpu-layers N layers +-b, --batch-size N batch +-ub, --ubatch-size N micro batch +--model-draft FNAME draft path +--chat-template-file FNAME template path +-rs, --rope-scaling TYPE scaling +--rope-freq-scale N scale +--custom-mode VALUE fork-specific mode +--override-kv KEY=TYPE:VALUE override metadata +--custom-switch, --no-custom-switch optional feature +--spec-type TYPE speculative mode +--port N server port +""" + + +def test_launch_custom_flags(tmp: Path) -> None: + from lib import launch + switches = schema.parse_help( + "-kvu, --kv-unified, -no-kvu, --no-kv-unified KV sharing\n" + "-ot, --override-tensor = tensor placement\n") + parsed = launch.parse_cli('-ot "blk.*=CPU" -no-kvu', switches) + check(launch.normalize(parsed, switches) == {"ot": "blk.*=CPU", "kv-unified": "false"}, + "short negative alias and compound placeholder survive help parsing") + flags = schema.parse_help(CUSTOM_LAUNCH_HELP) + template = tmp / "template with spaces.jinja" + opts = launch.parse_cli( + f"--chat-template-file '{template}' -rs yarn --custom-mode=a=b " + "--rope-freq-scale -1 --no-custom-switch -c 8192 -C 0xff", flags) + override = launch.parse_cli("--override-kv model.key=int:42", flags) + check(launch.flag_argv("override-kv", override["override-kv"], flags) + == ["--override-kv", "model.key=int:42"], "complex help placeholder takes a value") + check(opts["chat-template-file"] == str(template), "CLI: quoted path stays one value") + check(opts["custom-mode"] == "a=b" and opts["rope-freq-scale"] == "-1", + "CLI: equals and negative numbers preserved") + check(opts["c"] == "8192" and opts["cpu-mask"] == "0xff", + "CLI: case-sensitive short aliases preserved") + check(launch.flag_argv("no-custom-switch", "true", flags) == ["--no-custom-switch"], + "negative switch is not inverted") + check(launch.flag_argv("custom-switch", "false", flags) == ["--no-custom-switch"], + "false emits the negative switch") + for text in ("--typo 1", "--custom-mode", "--port 9000", "--model x.gguf", + "--custom-mode='unclosed", "--custom-mode 'a # comment'", + "--custom-mode a --custom-mode b", "--rope-freq-scale nope"): + try: + launch.parse_cli(text, flags) + rejected = False + except ValueError: + rejected = True + check(rejected, f"invalid launch arguments rejected: {text}") + dense = gguf.probe(_write_fake_gguf(tmp / "alias-dense.gguf", moe=False)) + pairs = wizard.pairs_for_custom_model( + {"ctx-size": "999999", "ncmoe": "8", "chat-template-file": "/other.jinja"}, + "/new.gguf", dense) + check(pairs["c"] == str(dense.n_ctx_trained) and "ctx-size" not in pairs, + "custom model: context alias clamped without competing keys") + check("n-cpu-moe" not in pairs and "chat-template-file" not in pairs, + "dense model does not inherit MoE or foreign template") + + +def test_tuner_custom_schema_and_globals(tmp: Path) -> None: + import argparse + m = _tune_module() + flags = schema.parse_help(CUSTOM_LAUNCH_HELP) + m._SCHEMA_CACHE["custom-server"] = flags + ini = tmp / "custom-tune.ini" + ini.write_text("""; leading global supported by wizard +version = 1 +custom-mode = global +[*] +ctx-size = 16384 +n-gpu-layers = 12 +[MyModel] +m = /test.gguf +LLAMA_ARG_CTX_SIZE = 8192 ; inline comment +C = 0xff +custom-mode = a=b +rope-scaling = yarn +no-custom-switch = true +""", encoding="utf-8") + opts = m.read_tune_options(ini, "mymodel", flags) + check(opts["c"] == "8192" and opts["n-gpu-layers"] == "12", + "tuner inherits globals; section env-alias overrides global context") + check(opts["cpu-mask"] == "0xff", "tuner does not lowercase -C into -c") + check("version" not in opts, "INI version metadata is not a server flag") + args = argparse.Namespace(keep_mmproj=False, allow_vision=False, allow_ot=False, + load_mode="default", ngl=99, threads=8, threads_batch=8, + flash_attn="auto", kv_cache_type="f16", kv_unified="auto", + jinja=False, cache_reuse=0, keep_checkpoints=False) + cmd = m.build_server_command("custom-server", opts, 9000, {}, args) + check(cmd[cmd.index("--custom-mode") + 1] == "a=b" and "--rope-scaling" in cmd, + "arbitrary schema flags actually reach server argv") + check("--no-custom-switch" in cmd and "--custom-switch" not in cmd, + "negative flag reaches tuner unchanged") + check(cmd.count("--ctx-size") == 1 and cmd[cmd.index("--ctx-size") + 1] == "8192", + "normalized axis emitted only once") + for bad in ("typo", "port"): + try: + m.build_server_command("custom-server", {**opts, bad: "1"}, 9000, {}, args) + rejected = False + except ValueError: + rejected = True + check(rejected, f"unknown/control key {bad} fails instead of silently disappearing") + edited = m.replace_section_keys(ini.read_text(), "mymodel", {"c": "4096"}, flags) + ini.write_text(edited) + check(m.read_tune_options(ini, "MyModel", flags)["c"] == "4096", + "apply updates env/long aliases, not a conflicting new short key") + + +def test_tuner_unknown_flag_preflight(tmp: Path) -> None: + import contextlib + import io + from unittest.mock import patch + m = _tune_module() + model = _write_fake_gguf(tmp / "preflight.gguf") + ini = tmp / "preflight.ini" + ini.write_text(f"[test]\nmodel = {model}\nc = 8192\ncustom-typo = 1\n") + binary = tmp / "preflight-server" + binary.write_text("#!/bin/sh\nexit 1\n") + binary.chmod(0o755) + m._SCHEMA_CACHE[str(binary)] = schema.parse_help(CUSTOM_LAUNCH_HELP) + stderr = io.StringIO() + with patch.object(sys, "argv", ["tuner", str(ini), "test", "--server", str(binary)]), \ + patch.object(m, "detect_server_caps", return_value={}), \ + patch.object(m, "gpu_mem", side_effect=AssertionError("GPU touched")), \ + contextlib.redirect_stderr(stderr): + try: + m.main() + rc = 0 + except SystemExit as exc: + rc = exc.code + check(rc == 2 and "custom-typo" in stderr.getvalue(), + "unsupported option fails during preflight before GPU work") + + +def test_wizard_new_model_to_tune(tmp: Path) -> None: + from unittest.mock import patch + m = _tune_module() + flags = schema.parse_help(CUSTOM_LAUNCH_HELP) + model = _write_fake_gguf(tmp / "No preset model.gguf", moe=False) + # Start with no models.ini at all, not just with an empty preset list. + env, calls = _wizard_env(tmp, ["1", str(model), "", "--custom-mode=a=b -rs yarn", + "y", "y", "4096", "n", "n", "n", "y"]) + seen = [] + + def run_tune(build, name, pairs): + saved = m.read_tune_options(tmp / "models.ini", name, flags) + seen.append((build, name, pairs, saved)) + return 0 + + with env, patch.object(wizard.schema, "load", return_value=(flags, {})), \ + patch.object(wizard.builds, "resolve_binary", return_value=(tmp / "server", "ik")), \ + patch.object(wizard.gguf, "find_mmproj_near", return_value=None), \ + patch.object(wizard, "_run_tune", side_effect=run_tune): + (tmp / "models.ini").unlink() + rc = wizard._setup_flow("http://127.0.0.1:8087") + check(rc == 0 and len(seen) == 1, "new GGUF reaches tune without an existing INI") + check(seen and seen[0][2]["c"] == seen[0][3]["c"] == "4096", + "confirmed context matches both budget input and actual tuner file") + check(seen and seen[0][3]["custom-mode"] == "a=b" + and seen[0][3]["rope-scaling"] == "yarn", + "custom model flags survive wizard -> INI -> tuner") + check(calls[0][0] == "validate" and calls[1][0] == "budget", + "new model is checked before tuning") + check(any(tmp.glob("models.ini.bak-*")), "confirmed context edit has a backup") + + +def test_wizard_tune_failures_stop_flow(tmp: Path) -> None: + from unittest.mock import patch + for failed in ("validate", "budget", "tune"): + env, calls = _wizard_env(tmp, ["1", "1", "y", "", "n", "n", "y"]) + with env: + def run_cli(*argv): + calls.append(argv) + return 7 if argv[0] == failed else 0 + with patch.object(wizard, "_run_cli", side_effect=run_cli), \ + patch.object(wizard, "_run_tune", return_value=7) as tune: + rc = wizard._setup_flow("http://127.0.0.1:8087") + check(rc == 7, f"{failed} failure propagated to caller") + check(tune.call_count == (1 if failed == "tune" else 0), + f"{failed} failure does not start subsequent tuning") + check("готово. загрузка вручную" not in env.text, "no false success after failure") + + +def test_tune_wrapper_relative_ini(tmp: Path) -> None: + import argparse + import runpy + from unittest.mock import patch + cli = runpy.run_path(str(ROOT / "bin" / "llamastery")) + cmd_tune = cli["cmd_tune"] + relative = Path("configs") / "model presets.ini" + with patch.object(cli["builds"], "resolve_binary", return_value=(tmp / "server", "test")), \ + patch.object(cli["subprocess"], "call", return_value=0) as call: + rc = cmd_tune(argparse.Namespace(ini=str(relative), section="new", build=None, extra=[])) + argv = call.call_args.args[0] + check(rc == 0 and argv[2] == str(relative.resolve()), + "CLI wrapper resolves INI before changing working directory") + check(call.call_args.kwargs["cwd"] == str(relative.resolve().parent), + "tuner results still go beside the INI") + + + + +def _current_upstream_help(): + return (ROOT / "tests/fixtures/upstream-2026-10-14-server-help.txt").read_text() + + +def test_tune_current_axes_capabilities(tmp: Path): + m = _tune_module() + flags = schema.parse_help(_current_upstream_help()) + meta = gguf.probe(_write_fake_gguf(tmp / "current-moe.gguf")) + args = _tune_args(moe_values="0,20,40", moe_cache_values="auto", + threads_batch_values="auto", cpu_ffn_values="", + op_offload_values="on,off", repack_values="off,on", + backend_sampling_values="off,on") + m.configure_search(args, {"n-cpu-moe": "20"}, flags, meta) + check({"moe_cache", "threads_batch", "backend_sampling", "op_offload", "repack"} + <= args.server_axes, "current server enables supported modern axes") + from unittest.mock import patch + bench_help = (ROOT / "tests/fixtures/upstream-2026-10-14-bench-help.txt").read_text() + with patch.object(m, "run_help", return_value=bench_help): + caps = m.detect_bench_caps("bench") + supported = m.supported_axes(args, flags, caps) + check(not ({"moe_cache", "threads_batch", "cpu_ffn", "backend_sampling"} & supported), + "upstream bench cannot silently test unsupported server-only axes") + check({"op_offload", "repack"} <= supported, "bench bool controls are supported separately") + dense = gguf.probe(_write_fake_gguf(tmp / "current-dense.gguf", moe=False)) + dense_args = _tune_args(cpu_ffn_values="0,4,8", moe_cache_values="auto") + m.configure_search(dense_args, {}, flags, dense) + check("cpu_ffn" in dense_args.server_axes and not {"moe", "moe_cache"} & dense_args.server_axes, + "dense models get dense-FFN axis, not useless MoE sweeps") + for overrides, model in (({"moe_cache_values": "256"}, dense), + ({"cpu_ffn_values": "4"}, meta), + ({"moe_values": "999"}, meta), + ({"repack_values": "perhaps"}, meta)): + try: + m.configure_search(_tune_args(**overrides), {}, flags, model) + rejected = False + except ValueError: + rejected = True + check(rejected, f"incompatible/invalid explicit axis rejected: {overrides}") + old = schema.parse_help("-c, --ctx-size N context\n") + try: + m.configure_search(_tune_args(moe_cache_values="512"), {}, old, meta) + rejected = False + except ValueError: + rejected = True + check(rejected, "explicit new flag on old fork fails before measurement") + m.configure_search(_tune_args(moe_cache_values="auto"), {}, old, meta) + check(True, "auto quietly skips unavailable axes on old forks") + + +def test_tune_dedup_and_compatibility(): + m = _tune_module() + check(m.variant_key({"moe": 20, "_axis": "moe"}) == + m.variant_key({"moe": 20, "_axis": "ubatch"}), + "same effective config deduplicated across different axis paths") + args = _tune_args(active_axes={"moe_cache", "fa", "threads_batch"}, + axis_options={"moe_cache": [0, 256, 512], "threads_batch": [4, 8]}, + model_is_moe=True, host_moe=False) + base = m.staged_base(args, {"n-cpu-moe": "20", "cache-type-k": "q8_0", + "cache-type-v": "q4_0", "threads-batch": "8"}) + base["moe_cache"] = 0 + variants = m.axis_variants(base, args, True) + check(any(v.get("moe_cache") == 256 for v in variants), "MoE cache participates in real candidate generation") + check(not any(v["fa"] == "off" for v in variants), "quantized V + FA off pruned before GPU load") + tb = [v for v in variants if v["_axis"] == "threads_batch"] + check(tb and tb[0]["threads"] == base["threads"], "prefill threads do not alter decode threads") + check(m._with_axis(base, "threads", 3)["threads_batch"] == 8, "decode threads do not alter prefill threads") + base["moe"] = 0 + check(not any(v["_axis"] == "moe_cache" for v in m.axis_variants(base, args, True)), + "cache with no CPU experts is not benchmarked") + check(m._axis_value({"b": 4096, "ubatch": 512}, "b") == 4096, + "actual logical batch used for baseline comparison") + fair = m.fair_variants([{"_axis": "moe", "moe": i} for i in range(10)] + + [{"_axis": "moe_cache", "moe_cache": 256}]) + check(fair[1]["_axis"] == "moe_cache", "offload grid cannot monopolize the candidate budget") + + +def test_tune_bench_current_flags(): + from unittest.mock import patch + m = _tune_module() + help_text = (ROOT / "tests/fixtures/upstream-2026-10-14-bench-help.txt").read_text() + with patch.object(m, "run_help", return_value=help_text): + caps = m.detect_bench_caps("bench") + args = _tune_args(screen_repeats=2, screen_pp=4096, screen_tg=64, bench_fit_target=1024) + base = m.staged_base(args, {"cache-type-k": "q8_0", "cache-type-v": "f16"}) + base.update(op_offload="off", repack="on") + cmd = m.build_bench_command("bench", caps, "/m.gguf", 16384, base, args) + check("--ctx-size" not in cmd and cmd[cmd.index("--n-depth") + 1] == str(16384 - 4096 - 64), + "upstream bench uses real n-depth, not nonexistent ctx-size") + check(cmd[cmd.index("--fit-ctx") + 1] == "16384" and "--fit-target" in cmd, + "explicit fit respects target context after upstream #28331") + check(cmd[cmd.index("--no-op-offload") + 1] == "1" and cmd[cmd.index("--repack") + 1] == "1", + "bench uses numeric bool values, unlike server switches") + check(cmd[cmd.index("--cache-type-v") + 1] == "f16", "screening preserves mixed K/V baseline") + args.bench_fit_target = 0 + cmd = m.build_bench_command("bench", caps, "/m.gguf", 8192, base, args) + check("--fit-ctx" not in cmd and "--fit-target" not in cmd, + "fit disabled by default; it must not silently alter searched axes") + + +def test_tune_staged_budget_baseline_and_failures(): + m = _tune_module() + args = _tune_args(active_axes={"moe_cache", "threads_batch"}, + axis_options={"moe_cache": [0, 256, 512], "threads_batch": [4, 8, 16]}, + model_is_moe=True, host_moe=False, refine_rounds=3, min_gain=0, + reserve=1024) + base = {**m.default_variant(args), "moe": 20, "moe_cache": 0} + seen = [] + def evaluate(v): + seen.append(dict(v)) + # One failed variant must never be retried even in later rounds. + ok = v.get("moe_cache") != 512 + return {"ok": ok, "min_observed_free_mib": 1800, + "deep": {"gen_tps": 30 + v.get("moe_cache", 0) / 64, + "prefill_tps": 100 + v["threads_batch"]}} + results = m.staged_search(base, args, evaluate, limit=6, + seeds=[{**base, "_axis": "fake"}]) + check(seen[0] == base, "first server measurement is the actual preset, including without bench") + check(len(results) <= 6 and len({m.variant_key(v) for v in seen}) == len(seen), + "hard server budget and dedup include baseline, failures and seeds") + check(any(v.get("moe_cache") == 256 for v in seen), "new axis is actually measured, not merely listed") + seen.clear() + m.staged_search(base, args, evaluate, limit=1) + check(seen == [base], "one-candidate budget measures baseline only") + + +def test_tune_cache_budget_and_measurement(tmp: Path): + meta = gguf.probe(_write_fake_gguf(tmp / "cache-budget.gguf")) + base = {"model": str(meta.path), "c": "8192", "n-cpu-moe": "20"} + cached = {**base, "moe-cache-mib": "512"} + a, b = budget.estimate(base, meta), budget.estimate(cached, meta) + check(abs(b.total_gb - a.total_gb - .5) < 1e-8 and b.moe_cache_gb == .5, + "MoE cache adds its VRAM budget instead of looking free") + for key, value in (("moe-cache-mib", "512"), ("n-cpu-ffn", "8"), + ("backend-sampling", "on"), ("op-offload", "off"), ("repack", "off")): + check(measure.signature(base) != measure.signature({**base, key: value}), + f"measurement identity includes {key}") + + +def test_tune_current_upstream_mock_campaign(tmp: Path): + """Exercise main end-to-end, but never start a server or use a GPU.""" + import contextlib + import io + from unittest.mock import patch + m = _tune_module() + root = tmp / "current-campaign" + root.mkdir(exist_ok=True) + model = _write_fake_gguf(root / "model.gguf") + binary = root / "llama-server" + binary.write_text("#!/bin/sh\nexit 99\n") + binary.chmod(0o755) + ini = root / "models.ini" + ini.write_text(f"[test]\nmodel = {model}\nc = 8192\nn-cpu-moe = 20\n" + "cache-type-k = q8_0\ncache-type-v = f16\nubatch-size = 1024\n") + bench_help = (ROOT / "tests/fixtures/upstream-2026-10-14-bench-help.txt").read_text() + bench_calls, server_calls = [], [] + def help_for(binary): + return bench_help if "bench" in str(binary) else _current_upstream_help() + def bench(tool, caps, model, ctx, v, args): + bench_calls.append(m.build_bench_command(tool, caps, model, ctx, v, args)) + rows = [{"kind": k, "ts": speed, "sd": 0, "n_prompt": 4096, "n_gen": 64} + for k, speed in (("pp", 100), ("tg", 30))] + return rows, "[]" + def evaluate(binary, opts, ctx, v, args, run_id, caps): + server_calls.append(dict(v)) + cfg = {**opts, "c": str(ctx), "moe-cache-mib": str(v.get("moe_cache", 0))} + return {"ok": True, "config": cfg, "min_observed_free_mib": 2048, + "deep": {"gen_tps": 30 + v.get("moe_cache", 0) / 128, "prefill_tps": 100}} + argv = ["tuner", str(ini), "test", "--server", str(binary), + "--max-screen", "5", "--max-candidates", "9", "--refine-rounds", "3", + "--moe-values", "16,20,24", "--moe-cache-values", "0,256,512", + "--out", str(root / "results")] + with patch.object(sys, "argv", argv), patch.object(m, "run_help", side_effect=help_for), \ + patch.object(m, "find_tool", return_value=root / "llama-bench"), \ + patch.object(m, "run_llama_bench", side_effect=bench), \ + patch.object(m, "evaluate", side_effect=evaluate), \ + patch.object(m, "gpu_mem", return_value=(12288, 0, 12288)), \ + patch.object(m, "ram_available_mib", return_value=32000), \ + contextlib.redirect_stdout(io.StringIO()): + m.main() + check(0 < len(bench_calls) <= 5, "total screening + refine stays inside --max-screen") + check(0 < len(server_calls) <= 9 and server_calls[0]["moe"] == 20, + "end-to-end server search measures baseline within budget") + check(all("--moe-cache-mib" not in cmd for cmd in bench_calls), + "upstream bench never receives new server-only flag") + check(any(v.get("moe_cache", 0) > 0 for v in server_calls), + "upstream MoE cache axis reaches the actual server evaluation stage") + plans = list((root / "results").glob("*/plan.json")) + check(len(plans) == 1 and "moe_cache" in json.loads(plans[0].read_text())["server_axes"], + "campaign records effective capability-aware plan") + check("moe-cache-mib" not in ini.read_text(), "no --apply: original preset unchanged") + + + + +def test_tune_modern_argv_and_apply(tmp: Path): + from lib import launch + m = _tune_module() + flags = schema.parse_help(_current_upstream_help()) + m._SCHEMA_CACHE["modern-bin"] = flags + args = _tune_args(keep_mmproj=False, allow_vision=False, allow_ot=False, + load_mode="default", jinja="on", cache_reuse=0, keep_checkpoints=False) + opts = {"model": "/model.gguf", "c": "8192", "n-cpu-moe": "20", + "moe-cache-mib": "512", "op-offload": "off", "repack": "off", + "backend-sampling": "on"} + cmd = m.build_server_command("modern-bin", opts, 8090, {}, args) + check(cmd[cmd.index("--moe-cache-mib") + 1] == "512", "new MoE cache reaches server argv with value") + check("--no-op-offload" in cmd and "--no-repack" in cmd, + "new bool axes emit proper negative server switches") + check("--backend-sampling" in cmd and cmd[-1] == "--backend-sampling", + "backend sampling is a switch, not '--backend-sampling on'") + text = "[m]\nno-op-offload = true\nno-repack = true\nmoe-cache-mib = 0\n" + updates = {"op-offload": "on", "repack": "on", "moe-cache-mib": "256"} + new = m.replace_section_keys(text, "m", updates, flags) + ini = inifile.IniFile(tmp / "negative-apply.ini", new) + cfg = launch.effective_pairs(ini, "m", flags) + check(all(cfg[k] == v for k, v in updates.items()) and "no-op-offload" not in cfg, + "apply replaces negative aliases without leaving conflicting values") + check(launch.parse_cli('--gpu-layers auto', flags)["n-gpu-layers"] == "auto", + "current upstream --gpu-layers auto/all is not rejected as non-numeric") + + +def test_axes_learning_does_not_mix_models(): + from lib import axes + from unittest.mock import patch + def run(model, threads, speed, binary): + return {"ok": True, "config": {"model": model, "c": "8192", "t": str(threads)}, + "short": {"gen_tps": speed}, "binary_fingerprint": binary} + records = [run("a.gguf", 4, 20, "old"), run("b.gguf", 8, 200, "old"), + run("a.gguf", 8, 200, "new")] + with patch.object(axes, "_load_results", return_value=records): + learned = axes.learn(min_pairs=1) + check("threads" not in learned, "different models/builds cannot fabricate a thread speedup") + records.append(run("a.gguf", 8, 25, "old")) + with patch.object(axes, "_load_results", return_value=records): + learned = axes.learn(min_pairs=1) + check(learned["threads"]["pairs"] == 1 and learned["threads"]["tps_gain"] == 1.25, + "same model/context/build isolated pair still teaches axis priority") + + if __name__ == "__main__": raise SystemExit(main()) diff --git a/tools/tune_models.py b/tools/tune_models.py index 2b532e2..2595149 100755 --- a/tools/tune_models.py +++ b/tools/tune_models.py @@ -151,7 +151,7 @@ def allowed_keys_for(server_bin) -> set[str]: "kv-unified", "jinja", "cache-reuse", - "load-mode", + "fit", "load-mode", "moe-cache-mib", "n-cpu-ffn", "op-offload", "repack", "backend-sampling", } BENCH_FLAG_ALIASES = { @@ -165,6 +165,11 @@ def allowed_keys_for(server_bin) -> set[str]: "ub": ("--ubatch-size", "-ub"), "t": ("--threads", "-t"), "tb": ("--threads-batch", "-tb"), + "depth": ("--n-depth", "-d"), + "fit_ctx": ("--fit-ctx", "-fitc"), + "fit_target": ("--fit-target", "-fitt"), + "op_offload": ("--no-op-offload", "-nopo"), + "repack": ("--repack",), } @@ -231,6 +236,7 @@ def run_help(binary): def detect_server_caps(binary): text = run_help(binary) return { + "fit": has_flag(text, "--fit"), "model": has_flag(text, "--model", "-m"), "mmproj": has_flag(text, "--mmproj"), "mmproj-offload": has_flag(text, "--mmproj-offload"), @@ -390,7 +396,47 @@ def stop_process(process): "presence-penalty", "frequency-penalty", ) +# These options are emitted explicitly above the schema-driven tail. Never +# pass aliases a second time: they would override the searched candidate. +HANDLED_KEYS = { + "model", "mmproj", "image-min-tokens", "mmproj-offload", "no-mmproj-offload", + "ot", "load-mode", "c", "n-gpu-layers", "n-cpu-moe", "b", "ubatch-size", + "t", "threads-batch", "parallel", "fa", "cache-type-k", "cache-type-v", + "kv-unified", "no-kv-unified", "jinja", "cache-reuse", "ctx-checkpoints", + "checkpoint-min-step", "n-predict", +} _KIND_CACHE = {} +_SCHEMA_CACHE = {} + + +def server_schema(binary): + key = str(binary) + if key not in _SCHEMA_CACHE: + try: + from lib import schema + # Same environment as the actual server, including adjacent .so's. + _SCHEMA_CACHE[key] = schema.parse_help(run_help(binary)) + except ImportError: + _SCHEMA_CACHE[key] = {} + return _SCHEMA_CACHE[key] + + +def read_tune_options(path, section, flags): + """Use the same INI semantics as the wizard, including globals/comments.""" + try: + from lib.inifile import IniFile + from lib.launch import effective_pairs + except ImportError: + ini = configparser.ConfigParser(interpolation=None, strict=False, + inline_comment_prefixes=(";", "#")) + ini.optionxform = str + ini.read(path, encoding="utf-8-sig") + if section not in ini: + raise ValueError("Секция не найдена") + return {**(dict(ini["*"]) if "*" in ini else {}), **dict(ini[section])} + ini = IniFile(path, Path(path).read_text(encoding="utf-8-sig")) + return effective_pairs(ini, section, flags) + def _flag_kinds(binary): @@ -398,26 +444,16 @@ def _flag_kinds(binary): key = str(binary) if key in _KIND_CACHE: return _KIND_CACHE[key] - kinds = {} - try: - import sys as _sys - from pathlib import Path as _Path - root = _Path(__file__).resolve().parent.parent - if str(root) not in _sys.path: - _sys.path.insert(0, str(root)) - from lib import schema as _schema - flags, meta = _schema.load(binary) - if not meta.get("error"): - uniq = {id(v): v for v in flags.values()} - for f in uniq.values(): - kinds[f.canonical] = f.kind - except Exception: - kinds = {} + kinds = {f.canonical: f.kind for f in server_schema(binary).values()} _KIND_CACHE[key] = kinds return kinds def build_server_command(binary, opts, port, caps, args): + flags = server_schema(binary) + if flags: + from lib.launch import normalize + opts = normalize(opts, flags) cmd = [str(binary), "--host", "127.0.0.1", "--port", str(port)] cmd += ["--model", str(opts["model"])] @@ -505,25 +541,30 @@ def build_server_command(binary, opts, port, caps, args): if caps.get("checkpoint-min-step") and opts.get("checkpoint-min-step") is not None: cmd += ["--checkpoint-min-step", str(opts["checkpoint-min-step"])] - # ускорители и прочее, что тюнер не варьирует, — переносим из секции. - # Сверка со схемой ЭТОЙ сборки: флаг, которого нет в бинаре (например - # reasoning-effort на faks), пропускаем, а не роняем весь прогон - # неизвестным аргументом. Пустой kinds = схема недоступна, тогда - # предполагаем, что значение нужно (как раньше). + # Forward EVERY schema-known option not owned by the search, not merely + # a hard-coded whitelist. A missing required flag is an error, not a + # different model configuration silently benchmarked as the requested one. kinds = _flag_kinds(binary) - schema_known = bool(kinds) - for key in PASSTHROUGH_KEYS: - if key not in opts: + for key, value in opts.items(): + if key in HANDLED_KEYS: continue - val = str(opts[key]).strip() - canon = "--" + key - kind = kinds.get(canon) - if kind is None and schema_known: - continue - if kind == "flag" or val == "": - cmd.append(canon) + if flags: + from lib.launch import CONTROL, flag_argv + if key in CONTROL: + raise ValueError(f"управление сервером нельзя задавать в пресете: {key}") + cmd += flag_argv(key, value, flags) + elif key in PASSTHROUGH_KEYS: + canon = "--" + key + kind = kinds.get(canon) + if kinds and kind is None: + continue + if kind == "flag": + if not is_false(value): + cmd.append(canon) + else: + cmd += [canon, str(value)] else: - cmd += [canon, val] + raise ValueError(f"не удалось проверить флаг {key}: недоступна схема сборки") # mmproj и режим его выгрузки: гейтим --keep-mmproj, иначе текстовый # замер не должен платить память за зрение @@ -952,15 +993,22 @@ def evaluate(binary, base_opts, context, variant, args, run_id, caps, short_only "ubatch-size": str(ubatch), "t": str(variant.get("threads", args.threads)), "threads-batch": str(variant.get("threads_batch", args.threads_batch)), - "parallel": "1", + "parallel": str(variant.get("parallel", base_opts.get("parallel", "1"))), "fa": str(variant.get("fa", args.flash_attn)), "cache-type-k": str(variant.get("kv_cache_type", args.kv_cache_type)), - "cache-type-v": str(variant.get("kv_cache_type", args.kv_cache_type)), + "cache-type-v": str(variant.get("kv_cache_type_v", variant.get("kv_cache_type", args.kv_cache_type))), "kv-unified": str(variant.get("kv_unified", args.kv_unified)), - "jinja": str(args.jinja), + "jinja": str(variant.get("jinja", base_opts.get("jinja", args.jinja))), "cache-reuse": str(variant.get("reuse", args.cache_reuse)), }) + for key, ini_key in MODERN_AXES.items(): + if key in variant: + cfg[ini_key] = str(variant[key]) + # Never let the server's automatic fit silently change a measured axis. + if caps.get("fit"): + cfg["fit"] = "off" + # mmproj выбрасывается только если зрение не нужно ни для сохранения # (--keep-mmproj), ни для замера (--allow-vision): иначе вторая ветка # добавления --mmproj в build_server_command была недостижима, и @@ -989,6 +1037,7 @@ def evaluate(binary, base_opts, context, variant, args, run_id, caps, short_only "kv-unified", "jinja", "cache-reuse", + "fit", "moe-cache-mib", "n-cpu-ffn", "op-offload", "repack", "backend-sampling", "model", # замер не должен выдаваться за замер другой модели ) @@ -998,9 +1047,12 @@ def evaluate(binary, base_opts, context, variant, args, run_id, caps, short_only # absent-ключи не пишутся, а не роняют прогон "config": {key: cfg[key] for key in selected_config_keys if key in cfg}, "config_extra": { + **{k: v for k, v in cfg.items() if k not in selected_config_keys}, "load-mode": eff_lm if caps.get("load-mode") else "default", }, "log": str(log_path), + "search_variant": dict(variant), + "binary_fingerprint": getattr(args, "binary_fingerprint", None), } vram_samples = [] @@ -1095,6 +1147,8 @@ def evaluate(binary, base_opts, context, variant, args, run_id, caps, short_only warmup_tokens=args.warmup_tokens, ) + if not result["short"]["needle_ok"]: + raise RuntimeError("Короткая проверка извлечения не прошла — глубокая проба пропущена") if not short_only and deep_target > short_target + 1024: result["deep"] = probe_series( port, @@ -1214,12 +1268,21 @@ def build_bench_command(tool, caps, model, ctx, variant, args): "-n", str(args.screen_tg), ] - add_bench_flag(cmd, caps, "ctx", ctx) + if caps.get("ctx"): + add_bench_flag(cmd, caps, "ctx", ctx) + elif caps.get("depth"): + add_bench_flag(cmd, caps, "depth", max(0, ctx - args.screen_pp - args.screen_tg)) + # fit-ctx is only a fit lower bound, NOT a context-size flag. + if getattr(args, "bench_fit_target", 0): + if not (caps.get("fit_ctx") and caps.get("fit_target")): + raise ValueError("llama-bench не поддерживает --fit-target/--fit-ctx") + add_bench_flag(cmd, caps, "fit_target", args.bench_fit_target) + add_bench_flag(cmd, caps, "fit_ctx", ctx) add_bench_flag(cmd, caps, "ngl", variant.get("ngl", args.ngl)) add_bench_flag(cmd, caps, "moe", variant.get("moe", 0)) add_bench_flag(cmd, caps, "fa", variant.get("fa", args.flash_attn)) add_bench_flag(cmd, caps, "ctk", variant.get("kv_cache_type", args.kv_cache_type)) - add_bench_flag(cmd, caps, "ctv", variant.get("kv_cache_type", args.kv_cache_type)) + add_bench_flag(cmd, caps, "ctv", variant.get("kv_cache_type_v", variant.get("kv_cache_type", args.kv_cache_type))) ubatch = safe_int(variant.get("ubatch", 2048), 2048) batch = max(safe_int(variant.get("b", 2048), 2048), ubatch) @@ -1229,6 +1292,10 @@ def build_bench_command(tool, caps, model, ctx, variant, args): add_bench_flag(cmd, caps, "t", variant.get("threads", args.threads)) add_bench_flag(cmd, caps, "tb", variant.get("threads_batch", args.threads_batch)) + if "op_offload" in variant: + add_bench_flag(cmd, caps, "op_offload", 0 if is_true(variant["op_offload"]) else 1) + if "repack" in variant: + add_bench_flag(cmd, caps, "repack", 1 if is_true(variant["repack"]) else 0) return cmd @@ -1467,8 +1534,252 @@ def run_llama_sweep_bench(tool, caps, model, ctx, variant, args, log_path): } +# Internal variant key -> canonical INI key. New axes go through the same +# schema serializer as user flags, not hard-coded argv guesses. +MODERN_AXES = { + "moe_cache": "moe-cache-mib", "cpu_ffn": "n-cpu-ffn", + "threads_batch": "threads-batch", "op_offload": "op-offload", + "repack": "repack", "backend_sampling": "backend-sampling", +} +INTEGER_AXES = {"moe_cache", "cpu_ffn", "threads_batch"} +CORE_AXIS_FLAGS = { + "moe": "n-cpu-moe", "ubatch": "ubatch-size", "b": "batch-size", + "threads": "threads", "kv_cache_type": "cache-type-k", "fa": "flash-attn", +} +BENCH_AXIS_KEYS = { + "moe": "moe", "ubatch": "ub", "b": "b", "threads": "t", + "threads_batch": "tb", "kv_cache_type": "ctk", "fa": "fa", + "op_offload": "op_offload", "repack": "repack", +} + + +def configure_search(args, opts, flags, meta=None): + """Resolve model/flag constraints before any expensive measurement.""" + from lib.launch import resolve_option + args.model_is_moe = meta.is_moe if meta is not None else None + args.model_layers = meta.n_layer if meta is not None else 0 + args.host_moe = is_true(opts.get("cpu-moe", "off")) or bool(opts.get("ot")) + args.fixed_placement = args.host_moe + if args.model_layers: + args.max_cpu_moe = min(args.max_cpu_moe, args.model_layers) + if getattr(args, "moe_values", "") and any( + x > args.model_layers for x in csv_ints(args.moe_values, "moe-values")): + raise ValueError("--moe-values превышает число слоёв модели") + args.axis_options = {} + raw_names = { + "moe_cache": "moe_cache_values", "cpu_ffn": "cpu_ffn_values", + "threads_batch": "threads_batch_values", "op_offload": "op_offload_values", + "repack": "repack_values", "backend_sampling": "backend_sampling_values", + } + for key, attr in raw_names.items(): + raw = getattr(args, attr, "") + flag = resolve_option(flags, MODERN_AXES[key]) + explicit = raw not in ("", "auto") + if not flag: + if explicit: + raise ValueError(f"--{attr.replace('_', '-')}: сборка не поддерживает --{MODERN_AXES[key]}") + continue + if key == "moe_cache" and args.model_is_moe is not True: + if explicit and any(csv_ints(raw, attr)): + raise ValueError("MoE cache требует подтверждённой MoE-модели") + continue + if key == "cpu_ffn" and args.model_is_moe is not False: + if explicit and any(csv_ints(raw, attr)): + raise ValueError("n-cpu-ffn предназначен для dense-модели") + continue + if raw == "auto": + if key == "moe_cache": + values = [0, 256, 512] + elif key == "threads_batch": + n = max(1, os.cpu_count() or 1) + current = safe_int(opts.get("threads-batch"), args.threads_batch) + values = sorted({max(1, n // 2), n, current}) + else: + values = [] + elif not raw: + values = [] + elif key in INTEGER_AXES: + values = csv_ints(raw, attr) + minimum = 1 if key == "threads_batch" else 0 + if any(v < minimum for v in values): + raise ValueError(f"--{attr.replace('_', '-')}: значения должны быть >= {minimum}") + if key == "cpu_ffn" and args.model_layers and max(values) > args.model_layers: + raise ValueError("--cpu-ffn-values превышает число слоёв модели") + else: + values = list(dict.fromkeys(v.strip() for v in raw.split(","))) + if any(v not in ("on", "off") for v in values): + raise ValueError(f"--{attr.replace('_', '-')}: ожидается on,off") + # Repack/op-offload need a real negative flag, not omission. + if "off" in values and key != "backend_sampling" and not resolve_option(flags, "no-" + MODERN_AXES[key]): + raise ValueError(f"сборка не поддерживает --no-{MODERN_AXES[key]}") + args.axis_options[key] = values + raw_kv = getattr(args, "kv_values", "") + if raw_kv: + known = {"f16", "bf16", "q8_0", "q4_0", "q4_1", "q5_0", "q5_1", "iq4_nl"} + values = raw_kv.split(",") + if any(v.strip() not in known for v in values): + raise ValueError("--kv-values: неизвестный тип K/V") + for key in ("cache-type-k", "cache-type-v"): + if not resolve_option(flags, key): + raise ValueError(f"сборка не поддерживает --{key}") + args.server_axes = supported_axes(args, flags) + if getattr(args, "search", "staged") == "full": + if any(getattr(args, attr, "") not in ("", "auto") for attr in raw_names.values()): + raise ValueError("новые оси поддерживаются в --search staged; full — legacy-сетка") + + +def supported_axes(args, flags, bench_caps=None): + from lib.launch import resolve_option + allowed = {key for key, flag in {**CORE_AXIS_FLAGS, **MODERN_AXES}.items() + if resolve_option(flags, flag)} + if getattr(args, "model_is_moe", None) is not True or getattr(args, "fixed_placement", False): + allowed.discard("moe") + if getattr(args, "model_is_moe", None) is not True: + allowed.discard("moe_cache") + if getattr(args, "model_is_moe", None) is not False: + allowed.discard("cpu_ffn") + if not resolve_option(flags, "cache-type-v"): + allowed.discard("kv_cache_type") + if bench_caps is not None: + allowed = {key for key in allowed if bench_caps.get(BENCH_AXIS_KEYS.get(key, ""))} + if not bench_caps.get("ctv"): + allowed.discard("kv_cache_type") + return allowed + + +def compatible_variant(v, args): + if getattr(args, "model_is_moe", None) is False and v.get("_axis") in ("moe", "moe_cache"): + return False + if v.get("_axis") == "moe_cache" and safe_int(v.get("moe_cache")) > 0: + if not (safe_int(v.get("moe")) > 0 or getattr(args, "host_moe", False)): + return False + # Quantized V requires FA. Do not deliberately generate guaranteed failures. + if str(v.get("fa", "auto")) == "off" and str(v.get("kv_cache_type_v", v.get("kv_cache_type", "f16"))) not in ("f16", "bf16", "f32"): + return False + return True + + +def fair_variants(variants): + """One value per axis before a second value: offload cannot eat the budget.""" + groups = {} + for v in variants: + groups.setdefault(v.get("_axis", "seed"), []).append(v) + out = [] + while any(groups.values()): + for group in groups.values(): + if group: + out.append(group.pop(0)) + return out + + +def search_weights(args): + return {"balanced": (0.55, 0.30, 0.15), "gen": (0.80, 0.10, 0.10), + "prefill": (0.20, 0.65, 0.15), "vram": (0.35, 0.20, 0.45)}.get( + getattr(args, "optimize_for", "balanced"), (0.55, 0.30, 0.15)) + + +def staged_search(base, args, evaluate_one, limit, seeds=()): + """Budgeted coordinate search, also when bench is absent or incompatible. + + Every callback loads once, checks short retrieval first, and only then + performs the deep probe on the SAME server. Failed candidates are deduped. + """ + measured, results = set(), [] + best, best_score = dict(base), None + weights = search_weights(args) + + def measure(v): + nonlocal best, best_score + key = variant_key(v) + if key in measured or len(results) >= limit: + return + measured.add(key) + r = evaluate_one(v) + r["search_variant"] = dict(v) + results.append(r) + if r.get("ok"): + score = rank_score(r, weights) + if best_score is None or score > best_score: + best, best_score = dict(v), score + + if limit <= 0: + return results + measure(base) + rounds = max(1, getattr(args, "refine_rounds", 2) + 1) + for rnd in range(rounds): + if len(results) >= limit: + break + fresh = axis_variants(best, args, "moe" in getattr(args, "active_axes", ()), exclude=measured) + fresh = fair_variants(fresh) + if rnd == 0: + # Bench winners are hints, never a replacement for the actual baseline. + fresh = [v for v in seeds if variant_key(v) not in measured][:2] + fresh + # Allow cache growth only within measured spare VRAM (reserve stays intact). + best_result = next((r for r in results if r.get("ok") and + variant_key(r["search_variant"]) == variant_key(best)), None) + if best_result and best_result.get("min_observed_free_mib") is not None: + spare = max(0, best_result["min_observed_free_mib"] - getattr(args, "reserve", 1024)) + fresh = [v for v in fresh if v.get("_axis") != "moe_cache" or + safe_int(v.get("moe_cache")) - safe_int(best.get("moe_cache")) <= spare] + unique = {} + for v in fresh: + if compatible_variant(v, args): + unique.setdefault(variant_key(v), v) + fresh = list(unique.values()) + if not fresh: + break + # Reserve room for refinement instead of spending everything around base. + remaining = limit - len(results) + quota = max(1, (remaining + (rounds - rnd) - 1) // (rounds - rnd)) + before = best_score + for v in fresh[:quota]: + measure(v) + # No promising improvement AND all immediate neighbours tested: stop. + if len(fresh) <= quota and before is not None and best_score is not None: + if best_score - before < getattr(args, "min_gain", 0.02) * max(abs(before), 1e-9): + break + return results + + +def run_staged_validation(args, opts, caps, contexts, selected): + args.active_axes = args.server_axes + base = default_variant(args) if args.ignore_preset else staged_base(args, opts) + # Optional axes start from documented defaults, only if schema supported. + for key, value in (("moe_cache", 0), ("cpu_ffn", 0), ("op_offload", "on"), + ("repack", "on"), ("backend_sampling", "off")): + if key in args.server_axes and args.axis_options.get(key): + base.setdefault(key, value) + results = [] + for i, ctx in enumerate(sorted(contexts, reverse=True)): + remaining = args.max_candidates - len(results) + count = len(contexts) - i + limit = remaining // count + if limit < 1: + break + def evaluate_one(v): + run_id = len(results) + 1 + print(f"[staged {run_id}/{args.max_candidates}] ctx={ctx} {v}", flush=True) + r = evaluate(args.server, opts, ctx, v, args, run_id, caps) + results.append(r) + (args.out / "results.json").write_text(json.dumps(results, indent=2, ensure_ascii=False), encoding="utf-8") + return r + staged_search(base, args, evaluate_one, limit, seeds=selected) + return results + + def variant_key(variant): - return json.dumps(variant, sort_keys=True, ensure_ascii=False) + # Search metadata is NOT part of the effective configuration. Otherwise + # the same settings reached via different axes are benchmarked repeatedly. + config = {k: str(v) for k, v in variant.items() if not k.startswith("_")} + if "kv_cache_type" in config: + config.setdefault("kv_cache_type_v", config["kv_cache_type"]) + for key in ("fa", "kv_unified", "op_offload", "repack", "backend_sampling"): + if key in config: + if is_true(config[key]): + config[key] = "on" + elif is_false(config[key]): + config[key] = "off" + return json.dumps(config, sort_keys=True, ensure_ascii=False) def default_variant(args): @@ -1558,7 +1869,7 @@ def ubatch_value_list(args): # threads — важен, когда эксперты на CPU (это наш случай); # b — влияет, только если больше ubatch; в новых сборках n_batch # клампится в n_ubatch, поэтому ось последняя. -def knob_axes(present_flags=None): +def knob_axes(present_flags=None, learn=True): """Порядок осей: из реестра lib/axes.py, приоритет скорректирован замерами. Реестр — единственное место, где описаны ось, её флаг и ожидаемый @@ -1567,7 +1878,7 @@ def knob_axes(present_flags=None): """ from lib import axes as _axes try: - learned = _axes.learn() + learned = _axes.learn() if learn else {} except Exception as exc: # noqa: BLE001 — реестр осей не критичен # битый tune-results/**/results.json не должен ронять даже --help _sys.stderr.write(f"предупреждение: замеры осей не прочитаны: {exc}\n") @@ -1585,13 +1896,15 @@ def knob_axes(present_flags=None): return out -KNOB_AXES = knob_axes() +KNOB_AXES = knob_axes(learn=False) def axis_values(args, key, screen_moe_enabled): """Допустимые значения оси; пустой список — ось нечего крутить.""" + if key in MODERN_AXES: + return getattr(args, "axis_options", {}).get(key, []) if key == "moe": - return moe_value_list(args, screen_moe_enabled) + return moe_value_list(args, screen_moe_enabled) if screen_moe_enabled else [] if key == "ubatch": return ubatch_value_list(args) if key == "b": @@ -1600,6 +1913,9 @@ def axis_values(args, key, screen_moe_enabled): raw = str(getattr(args, "batch_values", "") or "").strip() return [int(x) for x in raw.split(",") if x.strip()] if raw else [] if key == "kv_cache_type": + explicit = getattr(args, "kv_values", "") + if explicit: + return list(dict.fromkeys(x.strip() for x in explicit.split(",") if x.strip())) vals = [args.kv_cache_type] if args.try_f16 and "f16" not in vals: vals.append("f16") @@ -1619,7 +1935,7 @@ def axis_values(args, key, screen_moe_enabled): def _axis_value(variant, key): if key == "b": - return max(2048, int(variant.get("ubatch", 2048))) + return variant.get("b", max(2048, int(variant.get("ubatch", 2048)))) return variant.get(key) @@ -1629,16 +1945,19 @@ def _with_axis(variant, key, value): v["moe"] = int(value) elif key == "ubatch": v["ubatch"] = int(value) - v["b"] = max(2048, int(value)) + v["b"] = max(int(v.get("b", 2048)), int(value)) elif key == "b": v["b"] = max(int(value), int(v.get("ubatch", 2048))) elif key == "threads": v["threads"] = int(value) - v["threads_batch"] = max(int(v.get("threads_batch", 0) or 0), int(value)) + # Prefill threads are an independent axis, not coupled to decode. elif key == "kv_cache_type": v["kv_cache_type"] = str(value) + v["kv_cache_type_v"] = str(value) elif key == "fa": v["fa"] = str(value) + elif key in MODERN_AXES: + v[key] = value return v @@ -1650,16 +1969,19 @@ def axis_variants(base, args, screen_moe_enabled, exclude=None): seen = set(exclude or ()) seen.add(variant_key(base)) out = [] - for key, _rank, _why in sorted(KNOB_AXES, key=lambda a: -a[1]): + for key, _rank, _why in KNOB_AXES: + allowed = getattr(args, "active_axes", None) + if allowed is not None and key not in allowed: + continue current = _axis_value(base, key) for value in axis_values(args, key, screen_moe_enabled): if str(value) == str(current): continue v = _with_axis(base, key, value) - # метку оси ставим ДО подсчёта ключа: иначе ключ первого вызова - # не совпадёт с ключом exclude из следующего, и уже измеренное - # будет прогоняться заново + # Axis labels are diagnostic only; variant_key ignores them. v["_axis"] = key + if not compatible_variant(v, args): + continue k = variant_key(v) if k in seen: continue @@ -1685,6 +2007,8 @@ def staged_base(args, opts): v["b"] = max(safe_int(cfg.get("b"), v["b"]), v["ubatch"]) if "cache-type-k" in cfg: v["kv_cache_type"] = str(cfg.get("cache-type-k")) + if "cache-type-v" in cfg: + v["kv_cache_type_v"] = str(cfg["cache-type-v"]) if "fa" in cfg: fa = str(cfg.get("fa")).lower() if fa in ("on", "off", "auto", "true", "false", "1", "0"): @@ -1695,9 +2019,18 @@ def staged_base(args, opts): if "threads-batch" in cfg: v["threads_batch"] = safe_int(cfg.get("threads-batch"), v["threads_batch"]) if "n-gpu-layers" in cfg: - v["ngl"] = safe_int(cfg.get("n-gpu-layers"), v["ngl"]) + v["ngl"] = str(cfg["n-gpu-layers"]) if "kv-unified" in cfg: v["kv_unified"] = str(cfg.get("kv-unified")) + for key, ini_key in MODERN_AXES.items(): + if ini_key in cfg: + v[key] = (safe_int(cfg[ini_key]) if key in INTEGER_AXES else + "off" if is_false(cfg[ini_key]) else "on") + v["reuse"] = safe_int(cfg.get("cache-reuse", getattr(args, "cache_reuse", 0))) + for key, value in (("moe_cache", 0), ("cpu_ffn", 0), ("op_offload", "on"), + ("repack", "on"), ("backend_sampling", "off")): + if key in getattr(args, "server_axes", ()) and getattr(args, "axis_options", {}).get(key): + v.setdefault(key, value) return v @@ -1814,7 +2147,7 @@ def add(v): return out -def replace_section_keys(original, section, updates): +def replace_section_keys(original, section, updates, flags=None): if not updates: return original @@ -1833,17 +2166,23 @@ def replace_section_keys(original, section, updates): if match: if active: insert_index = len(output) - active = match.group(1) == section + active = match.group(1).lower() == section.lower() if active: found = True if active: km = key_line.match(line) - if km and km.group(2) in updates: - key = km.group(2) + key = km.group(2) if km else None + if key is not None: + try: + from lib.launch import normalize + key = next(iter(normalize({key: "true"}, flags or {}))) + except ImportError: + pass + if key in updates: seen.add(key) line = ( - f"{km.group(1)}{key}{km.group(3)}" + f"{km.group(1)}{key if km.group(2).lstrip('-').startswith('no-') else km.group(2)}{km.group(3)}" f"{updates[key]}{km.group(5) or ''}" ) @@ -2005,6 +2344,22 @@ def main(): p.add_argument("--threads-batch", type=int, default=16) p.add_argument("--try-threads-16", action="store_true") + p.add_argument("--moe-cache-values", default="auto", + help="MiB GPU-кэша CPU MoE-экспертов: auto или 0,256,512,1024; только при поддержке сборки") + p.add_argument("--cpu-ffn-values", default="", + help="явный список n-cpu-ffn для dense-моделей") + p.add_argument("--threads-batch-values", default="auto", + help="потоки префилла независимо от декодинга: auto или список") + p.add_argument("--op-offload-values", default="", + help="явный A/B on,off для операций над host-тензорами") + p.add_argument("--repack-values", default="", help="явный A/B on,off переупаковки весов") + p.add_argument("--backend-sampling-values", default="", + help="экспериментальный server-only A/B off,on; не меняет sampler chain") + p.add_argument("--kv-values", default="", + help="явные типы K/V-кэша, например q8_0,f16; фильтруются по совместимости с FA") + p.add_argument("--bench-fit-target", type=int, default=0, + help="MiB запаса auto-fit только screening; 0 = не менять раскладку автоматически") + p.add_argument("--try-4096", action="store_true") p.add_argument("--ubatch-values", default="", help="Явный список ubatch-size через запятую, например 2048,4096; " @@ -2052,7 +2407,7 @@ def main(): help="минимальный относительный прирост, ради которого " "делается следующий раунд (staged)") p.add_argument("--max-screen", type=int, default=24, - help="потолок кандидатов screening (staged)") + help="общий лимит screening, включая baseline и refinement") p.add_argument("--batch-values", default="", help="явные значения n_batch через запятую; по умолчанию " "ось b не крутится — она клампится в ubatch") @@ -2082,6 +2437,10 @@ def main(): if args.apply and not args.deep: p.error("--apply допускается только с --deep") + if args.max_screen < 1 or args.refine_rounds < 0: + p.error("--max-screen >= 1, --refine-rounds >= 0") + if not 0 <= args.min_gain < 1 or args.bench_fit_target < 0: + p.error("--min-gain должен быть в [0,1), --bench-fit-target >= 0") if args.max_candidates < 1: p.error("--max-candidates должен быть >= 1") if args.moe_step < 1: @@ -2123,20 +2482,10 @@ def main(): original_hash = hashlib.sha256(original_bytes).hexdigest() - ini = configparser.ConfigParser(interpolation=None, strict=False) - ini.read_string(original) - - if args.section not in ini: - p.error("Секция не найдена") - - opts = dict(ini[args.section]) - - unknown = set(opts) - allowed_keys_for(args.server) - if unknown: - p.error( - "Неизвестные ключи INI; добавьте явную поддержку или удалите: " - + ", ".join(sorted(unknown)) - ) + try: + opts = read_tune_options(args.ini, args.section, server_schema(args.server)) + except (OSError, ValueError, configparser.Error) as exc: + p.error(str(exc)) if not opts.get("model"): p.error("В секции нет model") @@ -2150,7 +2499,7 @@ def main(): p.error(f"Не найден модельный файл: {model_path}") opts["model"] = str(model_path) - if args.keep_mmproj and opts.get("mmproj"): + if (args.keep_mmproj or args.allow_vision) and opts.get("mmproj"): mmproj_path = Path(str(opts["mmproj"])).expanduser() if not mmproj_path.is_absolute(): mmproj_path = (args.ini.parent / mmproj_path).resolve() @@ -2228,6 +2577,8 @@ def main(): f"без --search-ctx с --deep --apply." ) + if len(contexts) > args.max_candidates: + p.error("--max-candidates должен покрывать хотя бы одну пробу на каждый контекст") if any(ctx < 4096 or ctx > 262144 for ctx in contexts): p.error("Контекст должен быть в пределах 4096..262144") @@ -2237,8 +2588,64 @@ def main(): if args.max_probe_tokens < args.short_probe_tokens: args.short_probe_tokens = max(512, args.max_probe_tokens // 2) + flags = server_schema(args.server) + if flags: + from lib.launch import resolve_option + for key, value in list(opts.items()): + f = resolve_option(flags, key) + if f is None: + p.error(f"флаг {key} не поддерживается выбранной сборкой") + if f.kind == "path" and value: + path = Path(value).expanduser() + opts[key] = str(path if path.is_absolute() else args.ini.parent / path) + if args.with_spec and opts.get("model-draft") and not Path(opts["model-draft"]).is_file(): + p.error(f"Не найден model-draft: {opts['model-draft']}") + + try: + from lib import gguf + model_meta = gguf.probe(opts["model"]) + except ImportError: + model_meta = None + except (OSError, ValueError, gguf.GGUFError): + model_meta = None + try: + configure_search(args, opts, flags, model_meta) + global KNOB_AXES + KNOB_AXES = knob_axes(set(flags)) + except ValueError as exc: + p.error(str(exc)) + if model_meta is None: + print("ВНИМАНИЕ: архитектура неизвестна — автоматические MoE/dense оси выключены.") + if args.model_is_moe is False or args.fixed_placement: + moe_sweep_server = False + + # Preflight before creating artifacts, unloading anything or starting GPU work. + try: + build_server_command(args.server, opts, 8080, server_caps, args) + except ValueError as exc: + p.error(str(exc)) + custom_launch = set(opts) - HANDLED_KEYS - set(PASSTHROUGH_KEYS) + # Optional server-only axes are explored after screening, never passed to + # upstream llama-bench which currently has no --moe-cache-mib. + # A preset already using any custom flag still requires server-only search. + if custom_launch or allow_ot or args.with_spec: + print("Screening через llama-bench пропущен: он не воспроизводит " + "дополнительные флаги сервера; подбор пойдёт через llama-server.") + args.skip_screening = True + args.out = args.out / (time.strftime("%Y%m%d-%H%M%S") + f"-{os.getpid()}") args.out.mkdir(parents=True, exist_ok=False) + binary_stat = args.server.stat() + args.binary_fingerprint = hashlib.sha256( + f"{args.server}:{binary_stat.st_size}:{binary_stat.st_mtime_ns}".encode()).hexdigest()[:16] + (args.out / "plan.json").write_text(json.dumps({ + "server": str(args.server), "binary_fingerprint": args.binary_fingerprint, + "model": opts["model"], "model_is_moe": args.model_is_moe, + "model_layers": args.model_layers, "server_axes": sorted(args.server_axes), + "axis_values": args.axis_options, "max_screen": args.max_screen, + "max_candidates": args.max_candidates, "search": args.search, + "contexts": contexts, + }, indent=2, ensure_ascii=False), encoding="utf-8") total, used, free = gpu_mem(args.gpu) print(f"GPU {args.gpu}: всего {total} MiB, свободно {free} MiB") @@ -2250,6 +2657,8 @@ def main(): bench_caps = {} screen_moe_enabled = False + if args.screen_only and (args.bench == "none" or args.skip_screening): + p.error("--screen-only: screening недоступен для этой конфигурации; сервер не запускался") if args.bench != "none" and not args.skip_screening: bench_tool = None sweep_tool = None @@ -2271,7 +2680,7 @@ def main(): if args.search == "staged": screen_moe_enabled = bool( server_caps.get("n-cpu-moe") and bench_caps_screen.get("moe") - and not allow_ot + and not allow_ot and args.model_is_moe is True and not args.fixed_placement ) if args.ignore_preset: _base = default_variant(args) @@ -2283,13 +2692,16 @@ def main(): f"{json.dumps(_base, ensure_ascii=False)}") print("порядок проверки (по убыванию прироста): " + ", ".join(k for k, _, _ in KNOB_AXES)) - candidates = axis_variants(_base, args, screen_moe_enabled) - candidates = candidates[:args.max_screen] + args.active_axes = supported_axes(args, server_schema(args.server), bench_caps_screen) + candidates = [_base] + fair_variants(axis_variants(_base, args, screen_moe_enabled)) + initial_budget = max(1, args.max_screen // (args.refine_rounds + 1)) + candidates = candidates[:initial_budget] else: candidates, screen_moe_enabled = make_screen_candidates( args, server_caps, bench_caps_screen, allow_ot, ) + candidates = candidates[:args.max_screen] needed_ctx = args.screen_pp + args.screen_tg + 64 screen_ctx = min(max(contexts), max(args.screen_ctx, needed_ctx)) if screen_ctx < needed_ctx: @@ -2367,6 +2779,10 @@ def main(): fresh = axis_variants(base_v, args, screen_moe_enabled, exclude=measured) + left = max(0, args.max_screen - len(measured)) + rounds_left = args.refine_rounds - rnd + 1 + round_budget = (left + rounds_left - 1) // rounds_left + fresh = fair_variants(fresh)[:round_budget] if not fresh: print(f"[refine {rnd}] новых вариантов нет — стоп") break @@ -2466,118 +2882,121 @@ def main(): }, indent=2, ensure_ascii=False)) return - candidate_limit = max(args.max_candidates, args.screen_top) * max(1, len(contexts)) - server_candidates = expand_server_candidates( - selected, - args, - server_caps, - allow_ot, - screen_moe_enabled, - candidate_limit, - ) + if args.search == "staged": + results = run_staged_validation(args, opts, server_caps, contexts, selected) + else: + candidate_limit = max(args.max_candidates, args.screen_top) * max(1, len(contexts)) + server_candidates = expand_server_candidates( + selected, + args, + {**server_caps, "n-cpu-moe": moe_sweep_server}, + allow_ot, + screen_moe_enabled, + candidate_limit, + ) - if not server_candidates: - server_candidates = [default_variant(args)] + if not server_candidates: + server_candidates = [default_variant(args)] + + results = [] + seen = set() + run_id = 0 + + # Быстрый предфильтр на уменьшенном контексте: отбрасываем OOM/медленные + # варианты до запуска дорогой full-context валидации. + max_ctx = max(contexts) + prefilter_ctx = None + if not args.no_prefilter: + want = args.prefilter_ctx or args.screen_ctx + if 4096 <= want < max_ctx: + prefilter_ctx = want + + if prefilter_ctx and server_candidates: + prefilter_results = [] + + for pf_idx, variant in enumerate(server_candidates, start=1): + run_id += 1 + print( + f"[P{pf_idx}/{len(server_candidates)}] prefilter ctx={prefilter_ctx} {variant}", + flush=True, + ) + result = evaluate( + args.server, + opts, + prefilter_ctx, + variant, + args, + run_id, + server_caps, + short_only=True, + ) + prefilter_results.append(result) + print(json.dumps(result, ensure_ascii=False), flush=True) + (args.out / "prefilter.json").write_text( + json.dumps(prefilter_results, indent=2, ensure_ascii=False), + encoding="utf-8", + ) - results = [] - seen = set() - run_id = 0 - - # Быстрый предфильтр на уменьшенном контексте: отбрасываем OOM/медленные - # варианты до запуска дорогой full-context валидации. - max_ctx = max(contexts) - prefilter_ctx = None - if not args.no_prefilter: - want = args.prefilter_ctx or args.screen_ctx - if 4096 <= want < max_ctx: - prefilter_ctx = want - - if prefilter_ctx and server_candidates: - prefilter_results = [] - - for pf_idx, variant in enumerate(server_candidates, start=1): - run_id += 1 - print( - f"[P{pf_idx}/{len(server_candidates)}] prefilter ctx={prefilter_ctx} {variant}", - flush=True, - ) - result = evaluate( - args.server, - opts, - prefilter_ctx, - variant, - args, - run_id, - server_caps, - short_only=True, - ) - prefilter_results.append(result) - print(json.dumps(result, ensure_ascii=False), flush=True) - (args.out / "prefilter.json").write_text( - json.dumps(prefilter_results, indent=2, ensure_ascii=False), - encoding="utf-8", - ) + survivors = [ + v for v, r in zip(server_candidates, prefilter_results) if r.get("ok") + ] + if survivors: + print( + f"\nПредфильтр прошли {len(survivors)}/{len(server_candidates)}; " + "далее полная проверка на максимальном контексте.", + flush=True, + ) + server_candidates = survivors + else: + print("\nПредфильтр не прошёл ни один вариант.", flush=True) + results = prefilter_results + server_candidates = [] + + # Larger contexts first, because --apply requires deep validation. + # BUGFIX: раньше был общий лимит max_candidates на все контексты — + # второй контекст почти никогда не тестировался. Теперь бюджет на контекст. + validation_contexts = sorted(contexts, reverse=True) + per_ctx_budget = max(1, args.max_candidates // max(1, len(validation_contexts))) + + full_idx = 0 + total_budget = args.max_candidates + for ctx in validation_contexts: + ctx_count = 0 + for variant in server_candidates: + if len(results) >= total_budget: + break + if ctx_count >= per_ctx_budget and len(validation_contexts) > 1: + break - survivors = [ - v for v, r in zip(server_candidates, prefilter_results) if r.get("ok") - ] - if survivors: - print( - f"\nПредфильтр прошли {len(survivors)}/{len(server_candidates)}; " - "далее полная проверка на максимальном контексте.", - flush=True, - ) - server_candidates = survivors - else: - print("\nПредфильтр не прошёл ни один вариант.", flush=True) - results = prefilter_results - server_candidates = [] - - # Larger contexts first, because --apply requires deep validation. - # BUGFIX: раньше был общий лимит max_candidates на все контексты — - # второй контекст почти никогда не тестировался. Теперь бюджет на контекст. - validation_contexts = sorted(contexts, reverse=True) - per_ctx_budget = max(1, args.max_candidates // max(1, len(validation_contexts))) - - full_idx = 0 - total_budget = args.max_candidates - for ctx in validation_contexts: - ctx_count = 0 - for variant in server_candidates: - if len(results) >= total_budget: - break - if ctx_count >= per_ctx_budget and len(validation_contexts) > 1: - break + key = (ctx, variant_key(variant)) + if key in seen: + continue + seen.add(key) - key = (ctx, variant_key(variant)) - if key in seen: - continue - seen.add(key) - - run_id += 1 - full_idx += 1 - ctx_count += 1 - print(f"[{full_idx}/{total_budget}] ctx={ctx} {variant}", flush=True) - - result = evaluate( - args.server, - opts, - ctx, - variant, - args, - run_id, - server_caps, - ) - results.append(result) + run_id += 1 + full_idx += 1 + ctx_count += 1 + print(f"[{full_idx}/{total_budget}] ctx={ctx} {variant}", flush=True) + + result = evaluate( + args.server, + opts, + ctx, + variant, + args, + run_id, + server_caps, + ) + results.append(result) - print(json.dumps(result, ensure_ascii=False), flush=True) - (args.out / "results.json").write_text( - json.dumps(results, indent=2, ensure_ascii=False), - encoding="utf-8", - ) + print(json.dumps(result, ensure_ascii=False), flush=True) + (args.out / "results.json").write_text( + json.dumps(results, indent=2, ensure_ascii=False), + encoding="utf-8", + ) - if len(results) >= args.max_candidates: - break + if len(results) >= args.max_candidates: + break (args.out / "results.json").write_text( json.dumps(results, indent=2, ensure_ascii=False), @@ -2679,7 +3098,7 @@ def main(): if int(updates["b"]) < int(updates["ubatch-size"]): updates["b"] = updates["ubatch-size"] - edited = replace_section_keys(original, args.section, updates) + edited = replace_section_keys(original, args.section, updates, server_schema(args.server)) if edited == original: print("Выбран исходный пресет; изменений не требуется.") return