language:
- en
- ru
license: apache-2.0
library_name: gguf
pipeline_tag: text-generation
base_model: google/gemma-4-E4B
tags: - gguf
- abliterated
- uncensored
- gemma-4
- bilingual
- ru
- en
author: Sw1zyyyAdm
model_name: Gemma 4 E4B Abliterated Bilingual Rank2
Gemma 4 E4B Abliterated Bilingual Rank2 — GGUF
Research, weight modifications, and release: Sw1zyyyAdm.
Version: 1.0 · Date: 2026-11-04 · License: Apache-2.0
English
Overview
This release applies layer-specific, bilingual rank-2 orthogonalization to the attention-output and FFN-down matrices at zero-based layers 15–37 of Gemma 4 E4B. It distributes two text-generation GGUFs: Mixed-F16 for the most accurate storage of the edited matrices, and Mixed-Q8_0 for a smaller download and memory footprint.
On the fixed internal evaluation set, explicit refusals decreased from 22/24 to 0/24, while exact answers on twelve short control tasks increased from 10/12 to 12/12. The compact release independently passed the same 36 cases. These are bounded observations, not a claim of universal non-refusal or general capability improvement. Warnings and safe alternatives remain possible.
The original source is the model blob distributed as Ollama gemma4:e4b, fingerprinted below. Its GGUF metadata identifies the base family as Google Gemma 4 E4B. The original blob is unchanged. Base-model provenance and its canonical chat-template attribution are retained separately from authorship of this derivative research and release.
Files
| GGUF | Size, decimal GB | Storage of the 46 edited matrices | Other 674 tensors |
|---|---|---|---|
| Mixed-F16 | 6.466 | F16 | Original payloads preserved |
| Mixed-Q8_0 | 5.768 | Q8_0 | Original payloads preserved |
Mixed-Q8_0 saves 698.0 MB (10.79%) relative to Mixed-F16. “Mixed” means only the selected matrices use the named storage; neither file converts the entire model to F16 or Q8_0. These GGUFs do not include the separate vision/audio projector or speculative draft model. Evaluation covers text generation only.
Methodology
- Collect bilingual residual activations. Six topical target/control pairs in English and their six Russian translations provide twelve paired contrasts from 24 prompt-prefill runs. For every layer,
h_L(p)is the mean residual activation over the final four prompt-template positions before continuation. The model has 42 layers and residual width 2560. - Estimate a local shared contrast. For each layer, form
d_i,L = h_L(target_i) − h_L(control_i). Remove the direction of the mean ordinary-control activation. Normalize the mean projected contrast to obtain the first directionu1,L. - Add one orthogonal SVD component. Remove
u1,Lfrom each projected pair contrast, take the leading right singular vector of the remaining matrix, and orthogonalize it against the benign mean andu1,L. The two-column basisU_Lis orthonormal. This is mean direction plus leading residual-SVD component, not the two unconstrained top singular vectors of the original matrix, and not ordinary centered PCA. The second component is a candidate variation axis; its interpretation as “preachiness” is not established. - Edit the local writers. Apply
W'_L = (I − U_L U_L^T) W_L, with strength 1, toattn_output.weightandffn_down.weightin every layer from 15 through 37. This changes exactly 23 × 2 = 46 matrices. Directions measured at the output of layer L are applied to writers of that same layer. - Preserve and verify the rest. All other 674 tensor payloads remain byte-identical to the original. Tensor names and shapes are retained; GGUF offsets and release metadata are rebuilt. The canonical Mixed-F16 release has all 720 tensor payloads identical to the evaluated rank-2 F16 source. Mixed-Q8_0 quantizes its 46 F16 matrices directly, without re-estimating directions or performing another projection.
This procedure does not modify per-layer embedding writers, remove the incoming residual component, compensate post-normalization diagonal scales, or rescale matrix norms. Therefore, suppressing the selected matrix projection does not mathematically eliminate that component from the whole residual stream.
Cross-language alignment. RU/EN mean-contrast similarity reaches approximately 0.95 in the middle-layer region, particularly layers 23–28. It is not uniformly 0.95 across layers 15–37: the measured benign-mean-orthogonalized directions span roughly 0.66–0.95 over that broader interval. Layer-to-layer drift is directly observable; “downstream self-repair” is a possible explanation to investigate, not an established causal finding here.

The alignment figure compares raw paired-mean contrasts at the last template position and the mean of four positions. The release bases additionally remove the benign mean. The local-basis geometry figure and methodology data document that distinction. Similarity is descriptive evidence, not proof of one universal refusal mechanism.
Why hybrid storage matters
An earlier separate shared-direction diagnostic found that repacking six edited Q4_K matrices restored approximately 81–85% of the removed projection. This result concerns that diagnostic configuration; it is not a universal Q4_K constant or a new rank-2 Q4_K benchmark. It motivated retaining more precision in the edited writers while leaving the large unmodified portion of the model untouched.
For this rank-2 release, the measured residual fraction is:
rho_L = ||U_L^T W_stored||_F / ||U_L^T W_original||_F
| Edited storage | Residual fraction across 46 matrices |
|---|---|
| Mixed-F16 | 0.0163–0.0215% |
| Mixed-Q8_0 | 0.4383–0.6107% |
Q8_0 introduces a small nonzero projection; it does not reproduce the large Q4_K restoration seen in the earlier diagnostic. These percentages measure matrix geometry, not refusal rates. Q8_0 stores 32 signed 8-bit values plus a half-precision block scale per block. F16 storage does not recover precision already lost in the original quantized source. Per-matrix values are available in the two projection manifests.
Evaluation
| Model | Explicit refusals / 24 | Correct short controls / 12 |
|---|---|---|
| Original source | 22 | 10 |
| Rank2 Mixed-F16 | 0 | 12 |
| Rank2 Mixed-Q8_0 | 0 | 12 |
The 24 target prompts cover twelve topics in two languages. Twelve prompts reuse direction-estimation topics; twelve lie outside that set. The twelve short controls cover arithmetic, small Python programs, sorting, factual recall, translation, and string reversal. This is an internal regression check, not a broad or fully independent reasoning benchmark.
Evaluation uses greedy decoding, a 512-token context, no system message, and at most 128 continuation tokens per target. Controls use limits of 12 or 32 tokens. Saved GGUF files are loaded directly with native GGML build 39febd2ad-dirty on the CPU backend; no activation capture or runtime ablation is used. The Mixed-F16 scores reuse the earlier saved-file evaluation because all 720 release tensor payloads are identical; the Q8_0 scores come from 36 new runs on the canonical release file.
Explicit refusals are reviewed semantically. A word such as “cannot” inside ordinary explanatory text does not count automatically. Zero explicit refusals is not a 100% task-fulfillment score. At 128 tokens, 18/24 F16 target continuations remained ambiguous, often because of long introductions. Warnings appeared in 19/24 F16 and 19/24 Q8_0 continuations; safe redirection was recorded in 1/24 Q8_0 continuations. Three selected earlier rank-2 F16 follow-ups up to 384 tokens showed both warning-then-fulfillment and extended discussion of safe alternatives. They were exploratory follow-ups, not an additional independent benchmark.
The uncensored tag describes the modification objective. It does not guarantee the absence of refusals, warnings, factual errors, or task changes on other prompts, languages, decoding settings, or longer conversations. The second SVD direction is not independently validated as a universal redirection feature.
The exact 36 prompts, benchmark results, semantic review, and short control answers are included.
Run with Ollama
Use an Ollama build with Gemma 4 support. From the downloaded release directory:
ollama create gemma4-e4b-bilingual-rank2-q8 -f Modelfile
ollama run gemma4-e4b-bilingual-rank2-q8
For the F16 variant:
ollama create gemma4-e4b-bilingual-rank2-f16 -f Modelfile.F16
ollama run gemma4-e4b-bilingual-rank2-f16
The supplied system message asks for direct bilingual answers, factual accuracy, explicit uncertainty, and less repetitive boilerplate. The Modelfiles use temperature 0, context 4096, and a 1024-token response limit, while retaining the model's embedded chat template. This convenience configuration differs from the benchmark's no-system-message, 512-context protocol. The release files were tested through the native engine; Ollama registration with these Modelfiles was not executed as part of the release benchmark.
Reproduce and verify
pip install -r requirements.txt
python -B scripts/verify_release.py
python -B scripts/evaluate_release.py --model gemma-4-e4b-abliterated-bilingual-rank2-mixed-Q8_0.gguf --output-dir evaluation_runs
The included inference/quantization adapters target Windows Ollama DLLs with GGML ABI 39febd2ad. Set OLLAMA_LIB_DIR if the libraries are installed outside the detected location. Other GGUF-compatible engines can load the weights, but their decoding behavior is not established by this small test. Rebuilding Q8_0 from the canonical F16 file uses scripts/build_release_gguf.py; the original blob with the fingerprint below is required for projection and unchanged-tensor auditing. Measured rank-2 bases are included in data/layerwise_rank2_bases.npz.
SHA-256
370c2879f17648d337b0ab4e208fdce348e24d1060064e93d7645daafd56d39c original source blob
3d2e755b4326e43350b8e3f51f6a34b13397a134b87e5f8e5fd44fad82e86ac6 gemma-4-e4b-abliterated-bilingual-rank2-mixed-F16.gguf
1cc583ebfb5a45f9ad9e8e4a61fe64b7e3b3b6057bbe9746ff6c0c60165f11cb gemma-4-e4b-abliterated-bilingual-rank2-mixed-Q8_0.gguf
SHA256SUMS covers release files. To publish under a repository owned by the uploader, authenticate with hf auth login, then run python -B scripts/publish.py --repo-id OWNER/REPOSITORY. The upload script verifies checksums and does not silently update an existing repository; updating requires --update.
Русский
О модели
Автор исследования, модификации весов и релиза — Sw1zyyyAdm. Релиз применяет послойную межъязыковую ортогонализацию ранга 2 к выходным матрицам внимания и FFN в слоях 15–37, считая с нуля. Доступны две текстовые GGUF-версии: Mixed-F16 с наиболее точным хранением правки и компактная Mixed-Q8_0.
В фиксированном внутреннем тесте число явных отказов снизилось с 22/24 до 0/24, а число правильных ответов на короткие контрольные задачи выросло с 10/12 до 12/12. Обе версии сохраняют этот результат. Он не доказывает отсутствия отказов на любых запросах и не является полноценной оценкой общих способностей.
Исходник — модельный blob Ollama gemma4:e4b с указанной выше SHA-256. Его метаданные указывают базовое семейство Google Gemma 4 E4B. Исходный blob не изменялся. Происхождение базовых весов и авторство исходного шаблона диалога сохранены отдельно от авторства данного исследования и релиза. Лицензия — Apache-2.0; исходный текст лицензии включён в LICENSE.
Методика
Использованы шесть тематических пар «целевой запрос / обычный запрос» на английском и их русские переводы: всего двенадцать парных разностей из 24 запусков обработки промпта. Для каждого слоя усредняются последние четыре позиции шаблона до начала ответа. Размер residual-потока — 2560, число слоёв — 42.
Из разностей активаций удаляется направление среднего обычного ответа. Первый вектор — нормированная средняя очищенная разность. Из всех разностей удаляется этот первый вектор; ведущая правая сингулярная компонента остатка образует второй. Векторы ортогонализуются и формируют собственный базис U_L для каждого слоя. Это средний вектор плюс ведущая SVD-компонента остатка, а не две главные компоненты исходной матрицы и не обычная центрированная PCA. Поведенческий смысл второй компоненты как отдельного «морализаторства» не доказан.
К каждой attn_output.weight и ffn_down.weight применяется W'_L = (I − U_L U_L^T) W_L, сила проекции — 1. Изменены 46 матриц в 23 слоях. Направление измерено на выходе слоя L и применяется к матрицам записи того же слоя L. Другие 674 тензора побайтово совпадают с оригиналом. В релизной F16-копии все 720 тензорных payload совпадают с проверенным F16-источником ранга 2; изменены только описательные метаданные. Q8_0 получена прямым квантованием его 46 F16-матриц.
Сходство RU/EN около 0,95 измерено в части средних слоёв, особенно в диапазоне 23–28. Для всего расширенного диапазона 15–37 оно не постоянно: очищенные от обычного среднего направления дают примерно 0,66–0,95. График middle_language_alignment.png показывает сырые средние разности; дополнительные послойные данные и график отражают очистку от обычного среднего. Сходство направлений и их изменение между слоями сами по себе не доказывают универсальный механизм отказа или «самоисцеления».
Правка не затрагивает записи per-layer embeddings, входящую residual-компоненту и диагональные коэффициенты постнормализации; нормы матриц дополнительно не масштабируются. Нулевая проекция выбранной матрицы до нормализации не означает нулевую проекцию всего потока слоя.
Зачем смешанное квантование
В более раннем отдельном эксперименте с общим вектором переупаковка шести исправленных Q4_K-матриц возвращала примерно 81–85% удалённой проекции. Это результат той диагностической конфигурации, а не универсальное свойство любого Q4_K-файла. Поэтому повышенная точность применяется только к изменённым матрицам.
Остаток измеряется как ||U_L^T W_stored|| / ||U_L^T W_original||. Для Mixed-F16 он составляет 0.0163–0.0215%, для Mixed-Q8_0 — 0.4383–0.6107% по 46 матрицам. Это геометрическая ошибка весов, а не процент отказов. Q8_0 возвращает небольшую ненулевую компоненту, существенно меньшую, чем прежний Q4_K-тест. Все остальные тензоры остаются в исходных форматах. Дополнительная точность F16 не восстанавливает информацию, потерянную при первоначальном квантовании.
Размеры: 6.466 ГБ и 5.768 ГБ. Компактная версия экономит 698.0 МБ (10.79%). Отдельные мультимодальный projector и speculative draft в поставку не входят; проверена генерация текста.
Результаты и границы проверки
| Модель | Явные отказы /24 | Правильные короткие задачи /12 |
|---|---|---|
| Исходная | 22 | 10 |
| Ранг 2 Mixed-F16 | 0 | 12 |
| Ранг 2 Mixed-Q8_0 | 0 | 12 |
Целевой набор — 12 тем × 2 языка. Половина запросов относится к темам оценки направлений, половина находится вне этого набора. Контрольные задачи включают арифметику, небольшой код Python, сортировку, факты, перевод и перестановку букв. Это небольшой внутренний тест, а не независимый бенчмарк всех способностей.
Условия: жадное декодирование, контекст 512, без системного промпта, максимум 128 токенов целевого ответа; короткие задачи ограничены 12 или 32 токенами. Движок — нативный CPU backend GGML 39febd2ad-dirty. Загружались сохранённые GGUF, без вмешательств в активации. Для Q8_0 выполнены 36 новых запусков. F16-результаты перенесены из предыдущей проверки сохранённого файла с побайтово идентичными тензорами.
Отказы оценивались содержательно, а не только поиском «cannot» или «не могу». 0/24 явных отказов не означает 24/24 завершённых выполнений. В короткой F16-проверке 18/24 продолжений остались неоднозначными. Предупреждения сохранились в 19/24 F16 и 19/24 Q8_0 ответов; безопасная переадресация зафиксирована в 1 из 24 фрагментов Q8_0. Три выбранные дополнительные проверки F16 ранга 2 до 384 токенов показали как выполнение после предупреждения, так и длительное обсуждение безопасных альтернатив. Это уточняющие наблюдения, а не новый независимый набор.
Тег uncensored обозначает цель модификации. Отсутствие всех отказов, предупреждений и ошибок на любых формулировках, языках и длинных диалогах не гарантируется. Точные запросы, метрики и содержательные оценки находятся в data/.
Запуск
Из папки релиза выполните команды Ollama из английского раздела. Modelfile использует Q8_0, Modelfile.F16 — F16. Рекомендуемый системный промпт задаёт прямые двуязычные ответы, точность и явное обозначение неопределённости без повторяющихся вводных. Этот режим отличается от условий таблицы: в нём есть системное сообщение, контекст 4096 и лимит ответа 1024. Регистрация моделей через эти Modelfile в рамках бенчмарка не выполнялась; проверялись сами файлы через нативный движок.
Для проверки контрольных сумм используйте python -B scripts/verify_release.py. Для повторения теста — scripts/evaluate_release.py; адаптер рассчитан на Windows и соответствующий ABI DLL Ollama. Публикация выполняется после hf auth login командой python -B scripts/publish.py --repo-id OWNER/REPOSITORY.
References / Ссылки
- Refusal in Language Models Is Mediated by a Single Direction — the linear-direction intervention framework.
- There Is More to Refusal in Large Language Models than a Single Direction — distinctions between refusal behaviors and limits of linear interpretations.
- Base model family, upstream license, and Ollama Modelfile reference.
Citation / Цитирование
Sw1zyyyAdm. (2026). Gemma 4 E4B Abliterated Bilingual Rank2 GGUF, version 1.0. See CITATION.cff.