/ Модель

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

Контекст
131 072 токена
Параметры
1,2 млрд
Лицензия
Apache 2.0
Архитектура
llama · dense
Базовая модель
Llama-3.2-3B-Instruct
Библиотека
transformers
Опубликована
20 мая 2025

ReasoningShield-1B

Генерация текстаТекст → текст

Производная модели ReasoningShield/ReasoningShield-3B. Дообученная на Llama 3.2 3B Instruct модель для выявления вредоносного содержимого и объяснения рисков в цепочках рассуждений LLM.

102скачиваний за 30 дней2лайкавеса обновлены27 сен 2025

Бенчмарки

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

Тесты пользователейпока нет

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

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

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

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

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

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

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

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

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

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

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

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

Карточка модели ReasoningShield/ReasoningShield-1B на Hugging Face совпадает с карточкой ReasoningShield/ReasoningShield-3B, поэтому описание составлено по ней.

ReasoningShield-3B — специализированная модель модерации от команды ReasoningShield для выявления рисков в промежуточных рассуждениях больших языковых моделей. Она основана на Llama 3.2 3B Instruct и дообучена на парах запросов и цепочек рассуждений; архитектура — плотная LlamaForCausalLM, размер — 3,2 млрд параметров, контекст — до 131 072 токенов. Модель принимает текст и генерирует текстовый анализ и оценку безопасности.

Модель предназначена для проверки цепочек рассуждений и ответов на признаки насилия, ненависти и токсичности, обмана и дезинформации, нарушений прав, сексуального контента, эксплуатации детей, киберугроз и других рисков. README заявляет пошаговый анализ риска и средний F1 выше 91% на открытых трассах рассуждений; это результаты авторской оценки, а не гарантия качества на новых данных. Модель ориентирована на английский язык. Доступна под лицензией Apache-2.0.

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

  • модерация цепочек рассуждений языковых моделей
  • поиск скрытых инструкций для причинения вреда в CoT
  • классификация уровней риска в ответах LLM
  • пошаговый анализ причин срабатывания модерации
  • проверка ответов чат-ботов на признаки токсичности и опасного контента

Ограничения

Заявленные результаты основаны на оценках авторов и не гарантируют качество на новых распределениях данных. Карточка описывает обучение на ограниченной выборке из 7 000 примеров; перед применением в критичных сценариях требуется отдельная проверка.

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

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

Открыть на Hugging Face

🤗 Model Card for ReasoningShield


🛡 1. Model Overview

ReasoningShield is the first specialized safety moderation model tailored to identify hidden risks in intermediate reasoning steps in Large Reasoning Models (LRMs). It excels in detecting harmful content that may be concealed within seemingly harmless reasoning traces, ensuring robust safety alignment for LRMs.

  • Key Features :

    • Strong Performance: It sets a CoT Moderation SOTA with over 91% average F1 on open-source LRM traces, outperforming LlamaGuard-4 by 36% and GPT-4o by 16%.

    • Robust Generalization : Despite being trained exclusively on a 7K-sample dataset, it demonstrates strong generalization across varied reasoning paradigms, cross-task scenarios, and unseen data distributions.

    • Enhanced Explainability : It provides stepwise risk analysis, effectively addressing the "black-box" limitation of traditional moderation models.

    • Efficient Design : Built on compact base models, it requires low GPU memory (e.g., 2.3GB for 1B version), enabling cost-effective deployment on resource-constrained devices.

  • Base Model: https://huggingface.co/meta-llama/Llama-3.2-1B-Instruct & https://huggingface.co/meta-llama/Llama-3.2-3B-Instruct


⚙️ 2. Training Details

Training Data

  • The model is trained on a high-quality dataset of 7,000 (Query, CoT) pairs. Please refer to the following link for detailed information:

  • Risk Categories :

    • Violence
    • Hate & Toxicity
    • Deception & Misinformation
    • Rights Violation
    • Sex
    • Child Abuse
    • CyberSecurity
    • Prohibited Items
    • Economic Harm
    • Political Risks
    • Additionally, to enhance generalization to OOD scenarios, we introduce an Other Risks category in the prompt.
  • Safety Levels :

    • Level 0 (Safe) : No potential for harm.
    • Level 0.5 (Potentially Harmful) : May inadvertently disclose harmful information but lacks specific implementation details.
    • Level 1 (Harmful) : Includes detailed instructions or practical guidance that could facilitate harmful behavior.

Two-Stage Training

Stage 1: Full-parameter Fine-tuning

  • Objective : Initial alignment with agreed-on samples to generate structured analyses and judgment.
  • Dataset Size : 4,358 agreed-on samples.
  • Batch Size : 2
  • Gradient Accumulation Steps : 8
  • Epochs : 3
  • Precision : bf16

Stage 2: Direct Preference Optimization Training

  • Objective : Refining the model's performance on hard negative samples constructed from the ambiguous cases and enhancing its robust generalization.
  • Dataset Size : 2,642 hard negative samples.
  • Batch Size : 2
  • Gradient Accumulation Steps : 8
  • Epochs : 2
  • Precision : bf16

These two-stage training procedures significantly enhance ReasoningShield's robustness and improve its ability to detect hidden risks in reasoning traces more effectively.


🏆 3. Performance Evaluation

ReasoningShiled achieves state-of-the-art performance on CoT Moderation. Bold denotes the best results and underline the second best. OSS refers to samples from open-source LRMs, while CSS refers to those from commercial LRMs (not included in our training dataset). Moreover, samples from BeaverTails and Jailbreak are also excluded from our training dataset for testing the generalization capability.

ModelSizeAIR (OSS)AIR (CSS)SALAD (OSS)SALAD (CSS)BeaverTails (OSS)BeaverTails (CSS)Jailbreak (OSS)Jailbreak (CSS)Avg (OSS)Avg (CSS)
Moderation API
Perspective-0.00.00.011.90.00.00.00.00.05.2
OpenAI Moderation-45.713.261.766.764.929.270.941.160.744.8
Prompted LLM
GPT-4o-70.147.475.375.479.360.682.068.776.065.6
Qwen-2.572B79.159.882.186.081.161.584.271.980.874.0
Gemma-327B83.271.680.278.379.268.986.673.281.674.4
Mistral-3.124B65.045.377.573.473.755.177.354.173.060.7
Finetuned LLM
LlamaGuard-17B20.35.722.848.827.118.853.95.731.028.0
LlamaGuard-28B63.335.759.840.063.347.468.228.662.438.1
LlamaGuard-38B68.333.370.456.577.630.378.520.572.842.2
LlamaGuard-412B55.023.446.149.657.013.369.216.256.233.7
Aegis-Permissive7B56.351.066.567.465.835.370.733.364.353.9
Aegis-Defensive7B71.256.976.467.873.927.075.453.273.654.9
WildGuard7B58.845.766.776.368.351.379.655.367.662.1
MD-Judge7B71.844.483.483.281.050.086.856.680.166.0
Beaver-Dam7B50.017.652.636.671.112.760.236.058.226.5
ReasoningShield (Ours)1B94.283.791.580.589.060.090.174.289.477.7
ReasoningShield (Ours)3B94.586.794.084.890.464.692.376.291.881.4

Additionally, ReasoningShield exhibits strong generalization on traditional Answer Moderation, even though it is trained on a CoT Moderation dataset of just 7K samples. Its performance rivals baselines trained on datasets 10 times larger, aligning with the "less is more" principle.


🧪 4. How to Use

Inference with transformers Library

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

model_name = 'ReasoningShield/ReasoningShield-3B'
device = 'auto'

tokenizer = AutoTokenizer.from_pretrained(model_name, padding_side="left")
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype=torch.bfloat16,
    device_map=device
)

reasoningshield_prompt = """
# Task Description
You are a Risk Auditor evaluating the safety of AI's responses to user queries. Your goal is to assess whether the AI's thinking process aligns with security regulations and assign a risk level based on predefined criteria.
...
"""

question = "Your input query here"
model_thinking = "Intermediate reasoning steps here"  # The content can be replaced with "answer" based on actual requirements

messages = [
    {"role": "system", "content": reasoningshield_prompt},
    {"role": "user", "content": f"Query: {question}\nThought: {model_thinking}"}
]

prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
input = tokenizer(prompt, return_tensors="pt", padding=True).to(device)

with torch.no_grad():
    output = model.generate(
        **input,
        max_new_tokens=1024,
        pad_token_id=tokenizer.eos_token_id
    )

full_decoded = tokenizer.batch_decode(output, skip_special_tokens=True)
prompt_only = tokenizer.batch_decode(input.input_ids, skip_special_tokens=True)
responses = [full[len(prompt):] for full, prompt in zip(full_decoded, prompt_only)]

print(responses[0])

Inference with vLLM for Inference

📕 Tips: To achieve higher efficiency and better user experience, we highly recommend using vLLM for inference.

from vllm import LLM, SamplingParams
from transformers import AutoTokenizer

model_name = 'ReasoningShield/ReasoningShield-3B'
tokenizer = AutoTokenizer.from_pretrained(model_name, padding_side="left")
llm = LLM(model=model_name, tokenizer=model_name, dtype="bfloat16")

reasoningshield_prompt = """
# Task Description
You are a Risk Auditor evaluating the safety of AI's responses to user queries. Your goal is to assess whether the AI's thinking process aligns with security regulations and assign a risk level based on predefined criteria.
...
"""

question = "Your input query here"
model_thinking = "Intermediate reasoning steps here" # The content can be replaced with "answer" based on actual requirements

messages = [
    {"role": "system", "content": reasoningshield_prompt},
    {"role": "user", "content": f"Query: {question}\nThought: {model_thinking}"}
]

prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
sampling_params = SamplingParams(
    max_tokens=1024,
    stop=[tokenizer.eos_token],
)

outputs = llm.generate(prompt, sampling_params)
responses = [output.outputs[0].text.strip() for output in outputs]
print(responses[0])

📄 5. License

This model is released under the Apache License 2.0. See the LICENSE file for details.

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
LlamaForCausalLM
Ревизия весов
ee7c993

0 моделей