/ Модель

Характеристики

Лицензия
Apache 2.0
Базовая модель
Ternary-Bonsai-2-9B-gguf
Опубликована
24 окт 2026

Bonsai-2-9b-Shakespeare-SFT

Генерация текстаТекст → текст3 профессии
316скачиваний за 30 дней3лайкавеса обновлены24 окт 2026

Описание модели

Составлено на русском по карточке модели и метаданным Hugging Face

Модель анализирует git diff и формулирует краткое ревью кода в стиле трагического героя Шекспира.

Bonsai Shakespeare 9B — экспериментальная модель для анализа изменений кода в стиле трагедии Шекспира. Она создана как QAT LoRA дообучение ternary-модели Ternary-Bonsai-2-9B, после обучения влияние адаптера было записано непосредственно в 2-битные ternary-веса GGUF. Модель принимает git diff на английском языке и выдаёт краткий аналитический разбор с рекомендацией, обрамлённый речью трагического героя; для заданного стиля системный промпт не требуется.

В README сообщается, что модель обычно отвечает на 90–150 слов, а её персона сохранялась на 15 из 15 тестовых примеров. Техническая точность ограничена: модель находила правдоподобную проблему, но совпадала с проблемой, отмеченной человеком, примерно в половине случаев и иногда выдумывала ошибки. Для запуска нужен форк llama.cpp от PrismML с поддержкой ternary-тензоров типа 42; стандартный llama.cpp файл не загрузит. Лицензия — Apache-2.0.

Сценарии применения

  • стилизованное ревью git diff в трагическом шекспировском тоне
  • поиск возможных проблем в изменениях Python-кода
  • генерация кратких комментариев к pull request
  • создание демонстраций и развлекательных обзоров кода

Ограничения

Техническая точность невысока: в README указано, что модель правильно выявляла отмеченную человеком проблему примерно в половине проверенных случаев и иногда выдумывала ошибки. Для запуска требуется форк llama.cpp от PrismML с поддержкой ternary-тензоров типа 42; стандартный llama.cpp несовместим.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus

Бенчмарки пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь рядом с другими моделями теста

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Текст» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы по шкале 0–100.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

Bonsai Shakespeare 9B

This model is an experiment in QAT LoRA on a ternary model: can you fine-tune Ternary-Bonsai-2-9B while it only exists as 2-bit ternary weights?

Standard quantization-aware pipelines keep a higher-precision master copy and quantize on the way into each forward pass. Here there was no stored master copy. The base stayed as frozen ternary codes for the whole run, and the LoRA delta was trained directly against that grid. At the end the adapter was discarded and its effect was committed into the GGUF by rewriting the 2-bit codes in place. Installing Shakespeare cost 55,603,249 trit flips out of 6.9 billion weights (0.80%).

Shakespearean code review was chosen as the task because style transfer gives a clean signal to evaluate. Paste a git diff and the model answers with a short analytical think block, then a lament in the voice of a tragic hero, with the actual remedy spelled out at the end. Either the review opens with "Alas" or it doesn't, which makes the persona an unambiguous instrument for measuring whether ternary training worked.

The result is a plain GGUF with the same size, format, and inference cost as the original, with no adapter or sidecar weights to merge at serve time.

Example

Input: a raw git diff. The persona is baked into the weights, so no system prompt is required.

Output:

<think>
The diff changes `fetch_page` to return rows[:limit + 1] and removes the
empty-result guard, while `fetch_all` switches to while True with a blanket
except. The off-by-one returns one extra row per page, so the boundary row
appears on two consecutive pages...
</think>
Alas, poor pagination! This scroll doth turn but not for naught, for thou
dost slice `rows[:limit + 1]`, and so the last event is caught twice across
pages. One fate, yet doomed duplication: the same row shall live in both
scrolls, a ghost haunting two tombs.

Better cure this wound: fetch only `limit` rows, and let each page's tail
hold its own final row...

How it was trained

The whole pipeline runs from the original GGUF file alone. No reference fp16 checkpoint is needed.

  1. Artifacts from the GGUF. Hadamard sign vectors, the tokenizer, and the config are all rebuilt from GGUF metadata (generate_artifacts.py).
  2. Factored representation. The GGUF is decomposed into ternary codes, fp16 per-block scales, and dense sidecar tensors (extract_gguf.py).
  3. LoRA in rotated weight space. Each of the 200 rotated linear layers gets a rank-64 LoRA pair in f32. The base stays as frozen ternary codes. There is no fp16 master weight tensor; the master weight M = ternary + B@A is formed on the fly inside the forward pass.
  4. STE with hysteresis. The forward pass rounds the master weight onto the ternary grid, using a straight-through estimator so gradients reach the LoRA as if rounding were the identity. The rounding keeps a hysteresis band: a weight must pass 0.60 of a block scale to flip up, and fall below 0.40 to flip back. This suppresses the flip-flop noise that otherwise destabilizes training near rounding boundaries.
  5. Runtime Hadamard rotation. Activations are rotated with FWHT(x·s)/√4096 at each linear layer, and the weights live permanently in rotated space.
  6. Trit-flip merge. Training ends with one committed trit per weight, taken from the hysteresis state. The merge writes those trits back into the GGUF's 2-bit codes in place. Scales and metadata stay untouched, so what was evaluated is exactly what ships.

Training config

settingvalue
LoRA rank / alpha64 / 128
learning rate1e-4, cosine decay, 20 warmup steps
effective batch32 (2 × 16 accumulation)
epochs / steps3 / 870
hysteresis threshold0.60
trainable params~160M
data~9,300 diff + review pairs
wall clock21.4 h on a single 40GB GPU

The data comes from diffs harvested from ronantakizawa/github-codereview, quality-filtered, deduplicated, and capped at 2,048 diff tokens. Review comments were restyled into Shakespearean tragedy by a teacher model, and a separate teacher pass generated 80–120 word analytical think blocks that reason about the code change (never about the review). Loss is computed on the think and review tokens only.

Training dynamics

Loss fell from 2.31 to 1.40 over the run. Gradient norm peaked at 24 early in warmup, then settled around 3.8 for the rest of training. The flip curve is a gentle S: no flips for the first 20 steps while the LoRA grows from zero and the forward pass stays bit-identical to the base, steady commitment through the middle, then a hard flatten as the learning rate anneals. Total: 55.6M flips, 0.80% of rotated weights.

What we learned

  • Rank 16 could not hold a persona. Our first runs (rank 16, 1.5k examples) plateaued at loss 2.3 and produced 0/15 persona on held-out prompts without a system message. Rank 64 broke through to 1.5 and the persona appeared. The binding constraint was capacity.
  • Hysteresis works. Earlier plain-STE runs showed gradient norms climbing to 38 while loss rose. With hysteresis the gradient norm stabilizes and loss actually descends. The band costs a little stickiness, since weights parked between 0.5 and 0.6 never commit, which is why we settled on 0.60 rather than 0.75.
  • With ~10k examples, epoch 3 is optional. Epoch-boundary loss barely moves (1.42 to 1.39), so there is no memorization cliff. Two epochs would have been nearly as good.
  • Watch the token budget. The model thinks longer on hard diffs than its 80–120 word training target, usually around 90–150 words. Four of our first eval "failures" were simply the think block hitting the 400-token generation cap before the tragedy started. With enough room to think, persona consistency is 15/15.

Evaluation

Held-out diffs never seen in training, a plain "You are a code reviewer…" system prompt, and thinking enabled:

  • Persona consistency: 15/15. Every output opens its review in the tragic voice.
  • Think quality: analytical, grounded in the actual diff, with no persona leakage into the reasoning.
  • Technical substance: the weakest axis. The model reliably finds a plausible issue and dramatizes it, but it lands on the issue a human reviewer flagged about half the time, and it occasionally invents problems. Treat the technical content as a starting point.

Usage

This file needs PrismML's llama.cpp fork with support for type-42 ternary tensors. Stock llama.cpp cannot read it.

./llama-cli -m BonsaiShakespeareV3.gguf \
  --chat-template chatml \
  -p "<|im_start|>user
File: src/pagination.py (python)

<paste diff here><|im_end|>
<|im_start|>assistant
"

Tips:

  • A system prompt is optional. The persona lives in the weights, so the diff alone is enough. Adding a system prompt won't stop the tragedy.
  • Give it room to think. Budget at least 800 new tokens; the think block runs 90–150 words before the review starts.
  • Use greedy decoding for the most consistent persona.

Limitations

  • This is a ternary 2.2-bits-per-weight model and inherits every capability limit of the base quantization.
  • Single task, single persona. It reviews diffs as tragedy, and that is the whole job.
  • Technical accuracy is imperfect (see above). The persona is the main event.
  • It requires the custom inference fork and will not load in stock llama.cpp.
  • The training data is teacher-generated English prose over real GitHub diffs, so expect the usual teacher-artifact biases.

Files in this repo

pathcontents
BonsaiShakespeareV3.ggufThe model. Everything else is for inspection and reproduction.
training_scripts/Self-contained scripts that operate from the GGUF alone.
sft_data/train_v3.jsonl9,253 tokenized training examples.
sft_data/eval_v3.jsonl500 held-out examples.
sft_data/full_data.jsonlAll 9,753 examples with raw diff, think, and review text.

Inside training_scripts/:

  • generate_artifacts.py — Hadamard signs, tokenizer, and config from GGUF metadata
  • extract_gguf.py — GGUF to ternary codes, scales, and dense substrate
  • dataset.py — tokenization and batching for training and eval
  • model.py — ternary loader and the rotated Hadamard linear layer
  • lora.py — LoRA-STE training with hysteresis; writes lora_final.pt and qstate_final.pt
  • eval.py — generation over the held-out split
  • merge.py — trit-flip merge back into a GGUF

Reproducing this

From the original base GGUF, run everything from the repo root:

python training_scripts/generate_artifacts.py --gguf Ternary-Bonsai-2-9B-Q2_0.gguf
python training_scripts/extract_gguf.py
python training_scripts/lora.py
python training_scripts/eval.py --ckpt lora_out_v3/lora_final.pt --out eval_final.jsonl
python training_scripts/merge.py --qstate lora_out_v3/qstate_final.pt \
  --gguf Ternary-Bonsai-2-9B-Q2_0.gguf \
  --out BonsaiShakespeareV3.gguf

This uses the included sft_data/ split. Paths and hyperparameters are defined at the top of each script.

Credits

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

llama.cpp

Можно запустить

Подбираем GPU…

Ревизия весов
606a150

0 моделей