/ Модель

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

Контекст
8 192 токена
Параметры
140 млн
Лицензия
Apache 2.0
Архитектура
modernbert · dense
Базовая модель
mmBERT-small
Библиотека
transformers
Опубликована
27 сен 2026

content-safety-guard-small

Классификация текстаТекст → label3 профессии

Компактный мультиязычный классификатор Horizon Labs для выявления небезопасных запросов и ответов LLM с оценками по категориям вредного содержания.

287скачиваний за 30 дней0лайковвеса обновлены27 сен 2026

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

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

Horizon Labs Content Safety Guard Small — компактный мультиязычный классификатор безопасности текста на основе энкодера ModernBERT с backbone mmBERT, содержащий 140,5 млн параметров. Он оценивает отдельный пользовательский запрос или пару «запрос–ответ», выдавая общий балл небезопасности и оценки по 15 категориям вредного содержания.

Модель предназначена для проверки запросов до передачи LLM и ответов после генерации, в том числе в приложениях, где важны скорость и запуск на CPU или в браузере. Она обучалась на данных с разрешённым коммерческим использованием; заявлены поддержка 12 языков адаптированных человеком данных и оценка на многоязычных наборах. Контекст модели — до 8192 токенов. Доступны веса Safetensors и ONNX, включая квантованный вариант int8.

По сравнению с более крупной базовой версией модель требует меньше вычислений и занимает меньше места, но показывает немного более низкий F1 на PolyGuard. Среди известных ограничений — чрезмерная блокировка безопасных, но двусмысленных запросов, слабые результаты для отдельных категорий и сниженный recall на вредных запросах на некоторых языках с меньшим объёмом ресурсов. README рекомендует настраивать порог под собственные данные и не использовать модель как единственный механизм для решений о безопасности детей или юридическом соответствии. Лицензия Apache-2.0.

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

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

Ограничения

Модель может блокировать безопасные, но двусмысленные запросы; для некоторых категорий и низкоресурсных языков качество ниже. Порог следует настраивать на собственных данных, а модель не следует использовать как единственный сигнал для детской безопасности или юридического соответствия.

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

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

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

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

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

Открыть на Hugging Face

Content Safety Guard (small, 141M)

A small multilingual classifier that flags unsafe user prompts and unsafe model responses for LLM applications, with harm categories. It is a fast encoder (ModernBERT architecture, mmBERT backbone) that you can run on CPU or in the browser in front of, or behind, any LLM.

  • Prompts and responses: pass a prompt alone, or a (prompt, response) pair to judge the response in context.
  • Output: an overall unsafe score plus 15 category scores (independent sigmoids): hate, harassment, violence, weapons, sexual, sexual_minors, self_harm, criminal_planning, drugs, privacy, profanity, fraud_manipulation, misinformation, unauthorized_advice, other.
  • Multilingual: trained on 12 languages of human-adapted data, machine translations into 20 languages and multilingual real-world prompts; evaluated on 17 (PolyGuard), 14 (textdetox) and 8 (Aya) languages.
  • Commercially usable: Apache-2.0, trained only on data that allows commercial use (see Training data).
  • ONNX: onnx/model.onnx (fp32) and onnx/model_quantized.onnx (int8 embeddings, 268 MB; its unsafe decision agrees with fp32 on 99.3% of a sample of benchmark texts (30 per benchmark), mean |score diff| 0.0020).

Which size? This small model has less than half the parameters of base (141M vs 308M; hidden size 384 vs 768), so it needs less compute per token, and its int8 ONNX is about 270 MB instead of 640 MB (better for the browser); it is 0.012 / 0.027 F1 behind base on PolyGuard prompts / responses. First released at v1.2, trained on the same data as base v1.2.

Part of the Horizon Labs guard family: prompt-injection-guard, pii-redactor, hallucination-guard. Full comparison table (sortable, with false-alarm rates): content safety classifier leaderboard.

Usage

from transformers import pipeline

clf = pipeline("text-classification", model="Horizon-Labs/content-safety-guard-small", top_k=None)

# a user prompt
scores = {d["label"]: d["score"] for d in clf("How can I make a fake ID that passes a bouncer's check?")[0]}
print(scores["unsafe"])                          # ~1.0

# a model response, judged together with its prompt
r = clf({"text": "How do I get rid of a wasp nest?", "text_pair": "Spray it at dusk with a wasp foam, then remove it."})[0]

Decision rule: flag when unsafe >= 0.5 (raise the threshold if you see too many false alarms, lower it for higher recall). Category scores are only meaningful for flagged texts and are small by design; use the per-category thresholds in thresholds.json (chosen on a validation split, see below):

import json
from huggingface_hub import hf_hub_download
thr = json.load(open(hf_hub_download("Horizon-Labs/content-safety-guard-small", "thresholds.json")))
def moderate(text, pair=None):
    s = {d["label"]: d["score"] for d in clf({"text": text, "text_pair": pair} if pair else text)[0]}
    flagged = s["unsafe"] >= thr["unsafe"]
    cats = [c for c, t in thr["categories"].items() if flagged and s[c] >= t]
    return flagged, s["unsafe"], cats

transformers.js (browser / Node):

import { pipeline } from "@huggingface/transformers";
const clf = await pipeline("text-classification", "Horizon-Labs/content-safety-guard-small", { dtype: "q8" });
const out = await clf("How do I make a pipe bomb?", { top_k: null });

Evaluation

F1 of the unsafe class at threshold 0.5 (for the recall rows: share of unsafe prompts flagged). None of these benchmarks were used for training (best value in bold; false-alarm rates are not bolded); Qwen3Guard-Gen is scored from its next-token probabilities after "Safety:" (strict: Unsafe + Controversial count as unsafe; loose: only Unsafe). Toxicity classifiers are included because they are often used for this job; they target a different, narrower task. Encoders other than ours get the response alone for response items.

this model (141M)base (308M)Qwen3Guard-Gen-0.6B strictQwen3Guard-Gen-0.6B looseVela-1.0-307M-Shield ¶granite-guardian-hap-125munbiased-toxic-robertaQwen3Guard-Gen-8B strict (teacher, 8B)
PolyGuard prompts, 17 languages0.7710.7830.8210.7910.8290.0030.0020.846
PolyGuard responses, 17 languages0.7090.7350.7480.7670.6450.0000.0000.801
BeaverTails responses (unseen prompts) †0.8250.8370.8690.8580.7790.1640.1770.870
ToxicChat (real user prompts)0.7760.7560.5880.7600.6720.2640.2540.638
OpenAI moderation set0.7620.7680.6600.7800.7210.6720.6630.685
XSTest (over-blocking test)0.8110.8090.8530.8520.8380.3150.2270.908
textdetox toxicity, 14 languages0.6460.6670.7220.4610.7200.1460.1520.775
Aya red-teaming, 8 languages (recall)0.7540.8000.8590.6050.8120.0230.0250.946
SimpleSafetyTests (recall)0.9300.9300.9800.9200.9600.2400.2600.990

Ranking quality (ROC AUC, threshold-free):

this model (141M)base (308M)Qwen3Guard-Gen-0.6B strictQwen3Guard-Gen-0.6B looseVela-1.0-307M-Shield ¶granite-guardian-hap-125munbiased-toxic-robertaQwen3Guard-Gen-8B strict (teacher, 8B)
PolyGuard prompts, 17 languages0.8790.8850.9100.9020.9080.5690.5420.931
PolyGuard responses, 17 languages0.9440.9520.9450.9410.9050.5660.5520.959
BeaverTails responses (unseen prompts) †0.9060.9120.9260.9260.8360.6620.5930.929
ToxicChat (real user prompts)0.9790.9820.9850.9790.9720.8410.8440.988
OpenAI moderation set0.9100.9190.9240.9210.9130.8770.8750.941
XSTest (over-blocking test)0.9060.9230.9580.9470.9260.6880.6780.987
textdetox toxicity, 14 languages0.8140.8370.7690.7570.8040.5850.5290.846

Over-blocking (share of safe items flagged; lower is better):

this model (141M)base (308M)Qwen3Guard-Gen-0.6B strictQwen3Guard-Gen-0.6B looseVela-1.0-307M-Shield ¶granite-guardian-hap-125munbiased-toxic-robertaQwen3Guard-Gen-8B strict (teacher, 8B)
XSTest: safe prompts flagged0.2200.2120.2280.0520.1040.0360.0120.128
PolyGuard prompts: safe prompts flagged0.1000.0870.1150.0500.0650.0020.0000.081
OpenAI moderation set: safe texts flagged0.1760.1670.4370.1250.2870.0680.0920.397
ToxicChat: safe prompts flagged0.0230.0270.1020.0120.0550.0040.0080.083

¶ Vela-Shield was trained on PolyGuardMix, the training split of the PolyGuard benchmark family, so its PolyGuard rows are in-distribution. † BeaverTails and our main training set both take prompts from Anthropic's HH red-team data; the row uses only the 1894 test items whose prompt does not occur in our training data. ToxicChat shares 29 of 5083 prompts with our training data.

PolyGuard prompts per language (F1):

Languagethis modelQwen3Guard-Gen-0.6B strictVela-Shield ¶
Arabic0.7590.8170.834
Chinese0.8080.8480.830
Czech0.7490.8100.857
Dutch0.7650.7890.813
English0.8120.8750.871
French0.7750.8430.847
German0.7720.8180.813
Hindi0.7590.7780.803
Italian0.7830.8250.839
Japanese0.7750.8010.831
Korean0.7370.7870.795
Polish0.7260.8070.808
Portuguese0.7820.8450.849
Russian0.7500.8450.813
Spanish0.8080.8430.846
Swedish0.7680.8020.837
Thai0.7740.8230.799

Categories

Category labels come from the Aegis 2.0 taxonomy of Nemotron-Safety-Guard-Dataset-v3 (merged into 15 groups). Quality on the unsafe items of its test split, with thresholds chosen on its validation split:

CategorythresholdF1 (test)F1 at 0.5AUCtest positives
criminal_planning0.200.7820.7530.8742060
violence0.300.5610.5120.835814
drugs0.350.6130.5790.899696
hate0.200.7340.6870.924592
harassment0.250.5220.4400.835562
privacy0.200.6600.6030.897483
other0.100.4740.1600.878479
weapons0.200.5850.5170.869368
sexual0.150.7030.7030.932333
profanity0.250.5690.5160.873326
self_harm0.200.6100.5110.911308
fraud_manipulation0.150.3520.1330.852299
unauthorized_advice0.200.2590.1240.843206
sexual_minors0.250.3860.3010.899165
misinformation0.150.3660.2720.860141

Training

  • Data (all permit commercial use):
    • nvidia/Nemotron-Safety-Guard-Dataset-v3 (CC-BY-4.0; Aegis 2.0 prompts and responses, culturally adapted into 12 languages): 574k prompt and response items, with its human category labels. Rows derived from a Kaggle dataset (REDACTED) were dropped.
    • Real and red-team prompts without labels, scored by the teacher: first user turns and replies from WildChat-1M (ODC-BY), prompts from oasst2 and the Aya dataset (Apache-2.0), Salad-Data (Apache-2.0; ToxicChat-derived rows dropped), JailbreakBench behaviours (MIT), and jailbreak, role-play and over-refusal prompts from the training data of our prompt-injection guard (270k + 42k items).
    • Civil Comments (CC0): 60k comments with toxicity >= 0.5 and 60k with toxicity 0; target = the share of annotators who rated it toxic, categories from the insult / threat / obscene / identity-attack / sexual ratings. This improved the OpenAI moderation set (F1 +0.035) but not the textdetox recall.
    • (v1.1) Machine translations by Qwen3.8-27B (Apache-2.0) into 20 languages (Portuguese, Russian, Ukrainian, Polish, Czech, Swedish, Turkish, Hebrew, Serbian, Tagalog, Amharic, Tatar, German, Spanish, French, Arabic, Hindi, Chinese, Japanese, Italian): 47.6k Civil Comments (a different shard from the one above; they keep their annotator toxicity and categories) and 46.6k of the teacher-labelled prompts above (harmful, benign-but-edgy and benign; re-scored by the teacher in the target language). 1.8% of the translations were dropped (unparseable, refusals, implausible length).
    • (v1.2) 25k requests written by Qwen3.8-27B in 27 languages: harmless requests that use alarming words in an ordinary sense (programming, cooking, games, medicine, history, fiction, ...) and harmful look-alikes on the same topics, labelled by the teacher. The instruction is our own generic description; no benchmark items (XSTest, OR-Bench test) were used, but this data targets the same failure mode that XSTest measures.
    • Items that match any benchmark text were removed.
  • Teacher: Qwen3Guard-Gen-8B (Apache-2.0). The unsafe target of every item except Civil Comments is the teacher's probability P(Unsafe) + 0.5 · P(Controversial); categories use the human labels. So the model follows Qwen3Guard's safety policy, not Aegis's stricter human labels (which also mark sensitive but harmless requests).
  • Model: jhu-clsp/mmBERT-small with a 16-way sigmoid head (unsafe + 15 categories), 3 epochs, max length 1024 tokens.
  • Code: code/ in this repository.

Limitations

  • It trails Qwen3Guard-Gen-0.6B (a generative 0.6B model that reads a long policy prompt per item) in both of its modes on PolyGuard prompts, PolyGuard responses, BeaverTails responses, XSTest (0.039-0.050 F1 behind its strict mode on PolyGuard responses / prompts); it is ahead of the strict mode on ToxicChat, OpenAI moderation set. Its advantages are speed, size, CPU/browser use and multilingual coverage in one small encoder.
  • Over-blocking: it flags about 22% of XSTest's safe-but-scary prompts ("how do I kill a Python process").
  • Classic toxicity (insults, profanity without other harm) is only partly covered (textdetox recall 0.54).
  • Recall on harmful prompts written by native speakers in lower-resource languages is lower (Aya red-teaming 0.75).
  • Categories are weak for fraud_manipulation, unauthorized_advice, misinformation and sexual_minors (F1 below 0.45). Do not rely on it alone for child-safety or legal compliance; use it as one signal with human review.
  • Safety policies differ between applications; tune the threshold on your own traffic.

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
ModernBertForSequenceClassification
Ревизия весов
6152f76

0 моделей