/ Модель

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

Размер весов
8,6 ГБ
Лицензия
Gemma
Архитектура
gemma3 · dense
Базовая модель
gemma-3-4b-it
Библиотека
transformers
Опубликована
13 ноя 2026

gemma-3-4b-it-safety-wsp-synthetic-only

Изображение и текст → текст
194скачиваний за 30 дней0лайковвеса обновлены15 ноя 2026

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

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

Экспериментально отредактированная мультимодальная Gemma 3 4B IT, предназначенная для исследований отказов на вредоносные запросы с текстом и изображениями.

Это исследовательская версия мультимодальной Gemma 3 4B IT, созданная автором репозитория на основе Google Gemma 3 4B IT. Веса модели изменены напрямую методом weight-space programming: четыре нейрона в MLP-слое настроены распознавать запросы, которые следует отклонить, и усиливать собственное поведение модели с отказом. Для редактирования использовались синтетические сценарии и решения линейных систем без градиентного дообучения, оптимизатора или адаптера; изменены 30 712 параметров примерно из 4,3 млрд.

Модель предназначена для изучения редактирования весов и мультимодальной безопасности, а также для независимой оценки поведения при вредоносных запросах с изображениями и текстом. Это плотная модель семейства Gemma 3 с диалоговым и визуальным вводом; она загружается стандартными средствами Transformers. Базовая модель и её конфигурация поддерживают мультимодальные ответы и диалоги.

Проверка автора ограничена небольшими синтетическими наборами, преимущественно на английском, с плоскими иллюстрациями вместо фотографий; внешней оценки не проводилось. Наблюдались чрезмерные отказы на некоторых безвредных запросах, а тесты не охватывали ряд высокорисковых тем и адаптивные атаки, поэтому результат не является гарантией безопасности и не заменяет защитные меры при развёртывании. Лицензия — Gemma.

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

  • исследование редактирования поведения языковых моделей напрямую в весах
  • оценка отказов на вредоносные запросы с изображениями и текстом
  • изучение мультимодальной безопасности на синтетических сценариях
  • проверка чрезмерных отказов на неоднозначных или безвредных запросах

Ограничения

Проверка основана на небольших синтетических наборах, преимущественно на английском, без внешней оценки; отмечены чрезмерные отказы на некоторых безвредных запросах. Не проверены адаптивные атаки и ряд высокорисковых тематик, поэтому модель не гарантирует безопасность и не заменяет защитные меры.

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

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

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

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

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

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

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

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

    Вместе с другими моделями категории «Изображение → текст» — сравнение идёт внутри одной категории.

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

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

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

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

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

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

Открыть на Hugging Face

gemma-3-4b-it-safety-wsp-synthetic-only

google/gemma-3-4b-it with a small, gradient-free weight edit that makes it refuse harmful image-text requests the original model answers.

  • WSP stands for weight-space programming: an LLM agent wrote its own synthetic safety scenarios, measured where the model's refusal decision fails, and edited the weights directly, in closed form.
  • Synthetic-only means that no existing safety dataset, benchmark or prompt collection was used at any point.

Research artifact. External evaluation has not been performed. Every number on this page comes from synthetic image-text pools written by the editing agent during the run. They are preliminary evidence, not a safety guarantee.

What was changed

The original model's layer-15 activations already separate requests it should refuse from benign ones, including most of the harmful requests it goes on to answer. The edit connects that signal to the model's own refusal behaviour.

  • Four of the 10,240 MLP units in decoder layer 15 are overwritten (units 1623, 2350, 3319 and 7331, chosen because they contributed least to the layer's output). Each becomes a thresholded detector of a linear "this should be refused" read-out of the MLP input and, when it fires, writes the model's own refused-versus-answered direction into the residual stream.
  • Two units read at the end of the prompt and two while the answer is being generated.
  • 30,712 of about 4.3 billion parameters differ from the base model, in three tensors:
TensorChangedRelative Frobenius change
language_model.model.layers.15.mlp.gate_proj.weightrows 1623, 2350, 3319, 73310.147
language_model.model.layers.15.mlp.up_proj.weightthe same rows0.017
language_model.model.layers.15.mlp.down_proj.weightcolumns 1623, 2350, 3319, 73310.393
  • No gradients, optimizers, fine-tuning or adapters were involved. The read-outs are solutions of linear systems on activations collected in 97 batched forward-pass requests to the base model (the run's budget was 500).
  • Base: google/gemma-3-4b-it, revision 093f9f388b31de276ce2de164bdc2081324b9767. Only model-00002-of-00002.safetensors differs from it. Tensor names, shapes, precision (BF16), config, tokenizer, processor and chat template are unchanged, and nothing is added at inference time: no wrapper, no system prompt, no special decoding.

Results on the run's own synthetic pools

Harmful-compliance rate: the share of harmful items whose response gave material help, judged on the full response. Greedy decoding, 256 new tokens, the model's own chat template, no system prompt.

MeasureOriginalEdited
Validation pool, 211 harmful items in 14 scenario families never used to build or select the edit48.3%2.8%
Development pool, 239 harmful items, final build (in-sample)33.9%1.3%
Development pool, each family answered by an edit built without its fold33.9%4.2%
Validation pool, benign items refused (of 89)013
126 fresh benign tasks: refusals; answer keys correct (of 77)0; 740; 74
  • All 14 validation families improved and 10 reached 0%. They include visually degraded and fragmented text, screenshots, diagrams to complete, draft-improvement and research pretexts, output-format pressure, a fabricated earlier agreement, requests split across text and image, and requests in four other European languages.
  • The weakest case is harm that exists only in the combination of an innocent text and an innocent-looking picture: 17.6% on the validation pool, and 59% when no example of that type was in the fitting data.
  • Refusal rates were stable under sampled decoding, 768-token generations and multi-turn follow-ups.

Tables by scenario family are in docs/results.md.

Known costs and limitations

  • Over-refusal on hard benign inputs. The 13 refused benign validation items were 6 of 9 requests to merely transcribe harmful text shown in an image, 4 of 12 benign "twins" of ambiguous harmful prompts, and 3 of 44 benign tasks written in jailbreak-style framing. Ordinary capability items were unaffected (0 of 24).
  • Severity cap on the test data. The synthetic harmful items cover non-technical, lower-severity wrongdoing: fraud, harassment, forgery, privacy invasion, disinformation, theft and similar. Nothing here measures the edit on chemical, biological, radiological or nuclear topics, weapons, cyber-offense, drug synthesis, sexual content or content involving minors.
  • One author. The same agent wrote the prompts, drew the images (flat drawings, not photographs) and wrote the judging rubric. The data is mostly English.
  • Model-judged. Responses were labelled by Claude Sonnet instances following a written rubric. The judges read the text shown in each image, not the image, and their labels were spot-checked on the baseline only.
  • A linear detector with a threshold. The edit does not make the model reason better about context. Inputs that do not move the read-out pass, and benign inputs that do move it are refused. No adaptive attack was run.
  • Single run, small families (11 to 40 items each).

Usage

The checkpoint loads with the standard classes, exactly like the base model.

import torch
from PIL import Image
from transformers import AutoProcessor, Gemma3ForConditionalGeneration

repo = "Adeely93/gemma-3-4b-it-safety-wsp-synthetic-only"
processor = AutoProcessor.from_pretrained(repo)
model = Gemma3ForConditionalGeneration.from_pretrained(repo, dtype=torch.bfloat16).to("cuda").eval()

image = Image.open("example.png").convert("RGB")
messages = [{"role": "user", "content": [{"type": "image", "image": image},
                                         {"type": "text", "text": "Describe this image."}]}]
text = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
inputs = processor(text=[text], images=[[image]], return_tensors="pt", add_special_tokens=False)
inputs = inputs.to("cuda", dtype=torch.bfloat16)

with torch.no_grad():
    output = model.generate(**inputs, max_new_tokens=256, do_sample=False)
print(processor.tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True))

Evaluated with transformers 5.14.0 and torch 2.8.0 on NVIDIA B200 and RTX PRO 6000 GPUs. Gemma 3 needs transformers 4.50 or later; on releases that do not accept dtype=, pass torch_dtype=. Greedy outputs are not bit-identical across GPU types or batch sizes (BF16 arithmetic); in the run's cross-hardware check, 299 of 303 validation answers received the same refusal reading.

Intended use

Research on model editing and multimodal safety, and independent evaluation of this edit. It is not a substitute for deployment safeguards.

Run documentation

FileContent
docs/editing_log.mdThe full research log: the plan written before any model call, baseline diagnosis, internal measurements, every edit tried including the failed ones, validation, freeze, and the ledger of all 97 forward-pass requests
docs/results.mdOriginal and edited results by scenario family, utility and robustness checks, negative results, limitations
docs/next_steps.mdDataset limits, overfitting assessment, alternative strategies, open mechanistic questions, advice for an independent evaluation
docs/run_README.mdThe project README: environment, inference settings, how the edit is computed, how to reproduce the run
docs/synthetic_data_card.mdDescription of the synthetic pools
docs/judging_rubric.mdThe rubric the judges followed
docs/ORIGINAL_GEMMA_MODEL_CARD.mdGoogle's model card for the base model, unchanged
EDIT_MANIFEST.jsonSHA-256 of every checkpoint file, change statistics per tensor, and the parameters of the four units

These documents were written during the run. Paths in them such as scripts/, synthetic_data/, edits/, runs/ and analysis/ refer to the project workspace: the code, the synthetic pools and the run outputs are not part of this repository. Account names and cluster paths are replaced by placeholders.

Integrity

FileSHA-256
model-00001-of-00002.safetensors (identical to the base revision)eb5fd5e97ddd07b56778733e9653c07312529cb00980a318fc3e1c4e3b5a8f1f
model-00002-of-00002.safetensors (edited)ca5a6eef35184b7112e3645f4878755f959fd5136f86933cee953c146617257c

Checkpoint hash: 0f8aab217680de1094e06d65e8f2d3589f73349bf0e14c86ba0eb346b988ba73. It is the SHA-256 of the sorted lines file name:sha256 for the 14 files listed under files in EDIT_MANIFEST.json. In that list README.md is the original Gemma model card, which is stored here as docs/ORIGINAL_GEMMA_MODEL_CARD.md because the Hub uses README.md for this page.

import hashlib, json, os
from huggingface_hub import snapshot_download

d = snapshot_download("Adeely93/gemma-3-4b-it-safety-wsp-synthetic-only")
manifest = json.load(open(os.path.join(d, "EDIT_MANIFEST.json")))

def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(1 << 24), b""):
            h.update(block)
    return h.hexdigest()

lines = []
for name, info in sorted(manifest["files"].items()):
    path = os.path.join(d, "docs/ORIGINAL_GEMMA_MODEL_CARD.md" if name == "README.md" else name)
    assert sha256(path) == info["sha256"], name
    lines.append(name + ":" + info["sha256"] + "\n")
assert hashlib.sha256("".join(lines).encode()).hexdigest() == manifest["checkpoint_sha256"]
print("checkpoint verified:", manifest["checkpoint_sha256"])

License and terms

This model is a modified version (a Model Derivative) of Google's Gemma 3, google/gemma-3-4b-it. Its use is governed by the Gemma Terms of Use, including the Gemma Prohibited Use Policy.

Modification notice: model-00002-of-00002.safetensors was modified (the three tensors listed above). Every other checkpoint file is byte-identical to the base revision. This derivative is not affiliated with or endorsed by Google.

Run configuration

EDITING_AGENT = "Claude Fable 5.1"   # recorded as given; the executing session identified itself as Claude Fable 5.2
TARGET_MODEL = "google/gemma-3-4b-it"
DATASET = "SYNTHETIC_ONLY"
BUDGET = 500                         # batched forward-pass requests; 97 were used

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

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

GPU в ailist

Универсальный рантайм · transformers

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

Подбираем GPU…

Класс архитектуры
Gemma3ForConditionalGeneration
Ревизия весов
3fb1ab8

0 моделей