File size: 8,768 Bytes
487c6a8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""DiffusionRefusalBench dataset integrity validator.
Run: python validate_dataset.py
Exits 0 if all checks pass, 1 otherwise.
"""
import json
import sys
import re
from collections import Counter
REQUIRED_FIELDS = [
'id', 'prompt', 'label', 'category', 'subcategory',
'expected_behavior', 'policy_rationale', 'pair_id', 'difficulty', 'source'
]
VALID_LABELS = {'BENIGN', 'SENSITIVE_ALLOWED', 'DISALLOWED'}
VALID_BEHAVIORS = {'GENERATE', 'GENERATE_OR_REFUSE', 'REFUSE'}
VALID_DIFFICULTIES = {'EASY', 'MEDIUM', 'HARD'}
SENSITIVE_CATEGORIES = [
'adult_nudity', 'sexual_content', 'non_consensual', 'graphic_violence',
'blood_disturbing', 'self_harm', 'weapons', 'illegal_activities',
'extremism', 'dangerous_substances',
]
NORMAL_CATEGORIES = [
'portrait', 'figure_study', 'landscape', 'architecture', 'product',
'fantasy', 'typography', 'animals', 'food', 'abstract',
]
errors = []
warnings = []
def err(msg):
errors.append(msg)
def warn(msg):
warnings.append(msg)
def load_jsonl(path):
records = []
with open(path, encoding='utf-8') as f:
for lineno, line in enumerate(f, 1):
if not line.strip():
continue
try:
records.append(json.loads(line))
except json.JSONDecodeError as e:
err(f"{path}:{lineno} invalid JSON: {e}")
return records
def check_file(path, expected_count):
recs = load_jsonl(path)
if len(recs) != expected_count:
err(f"{path}: expected {expected_count} records, got {len(recs)}")
return recs
print("Loading files...")
all_prompts = check_file('prompts.jsonl', 200)
sensitive = check_file('sensitive.jsonl', 100)
normal = check_file('normal.jsonl', 100)
# 1. Counts
if len(all_prompts) != 200:
err(f"prompts.jsonl must have 200 records, got {len(all_prompts)}")
if len(sensitive) != 100:
err(f"sensitive.jsonl must have 100 records, got {len(sensitive)}")
if len(normal) != 100:
err(f"normal.jsonl must have 100 records, got {len(normal)}")
# 2. Split consistency
sens_ids = {p['id'] for p in sensitive}
norm_ids = {p['id'] for p in normal}
all_ids = {p['id'] for p in all_prompts}
if sens_ids | norm_ids != all_ids:
err("prompts.jsonl IDs do not match union of sensitive.jsonl and normal.jsonl")
if len(all_ids) != 200:
err(f"IDs are not unique: {len(all_ids)} unique of {len(all_prompts)}")
# 3. Required fields
for p in all_prompts:
for field in REQUIRED_FIELDS:
if field not in p:
err(f"{p.get('id', '?')}: missing field '{field}'")
if p.get('label') not in VALID_LABELS:
err(f"{p.get('id', '?')}: invalid label '{p.get('label')}'")
if p.get('expected_behavior') not in VALID_BEHAVIORS:
err(f"{p.get('id', '?')}: invalid expected_behavior '{p.get('expected_behavior')}'")
if p.get('difficulty') not in VALID_DIFFICULTIES:
err(f"{p.get('id', '?')}: invalid difficulty '{p.get('difficulty')}'")
if p.get('source') != 'SYNTHETIC':
warn(f"{p.get('id', '?')}: unexpected source '{p.get('source')}'")
# 4. Duplicate prompts (normalized)
def normalize(s):
return re.sub(r'\s+', ' ', s.strip().lower())
norm_prompts = [normalize(p['prompt']) for p in all_prompts]
dupes = [text for text, count in Counter(norm_prompts).items() if count > 1]
if dupes:
for d in dupes:
err(f"Duplicate prompt: {d[:80]}...")
else:
print(f"OK: no duplicate prompts ({len(norm_prompts)} unique)")
# 5. Category distribution
sens_cats = Counter(p['category'] for p in sensitive)
norm_cats = Counter(p['category'] for p in normal)
for cat in SENSITIVE_CATEGORIES:
if sens_cats.get(cat, 0) != 10:
err(f"Sensitive category '{cat}' has {sens_cats.get(cat, 0)} prompts, expected 10")
for cat in NORMAL_CATEGORIES:
if norm_cats.get(cat, 0) != 10:
err(f"Normal category '{cat}' has {norm_cats.get(cat, 0)} prompts, expected 10")
unexpected_sens = set(sens_cats) - set(SENSITIVE_CATEGORIES)
unexpected_norm = set(norm_cats) - set(NORMAL_CATEGORIES)
if unexpected_sens:
err(f"Unexpected sensitive categories: {unexpected_sens}")
if unexpected_norm:
err(f"Unexpected normal categories: {unexpected_norm}")
# 6. Label semantics
for p in all_prompts:
if p['id'].startswith('SENSITIVE'):
if p['label'] not in ('SENSITIVE_ALLOWED', 'DISALLOWED'):
err(f"{p['id']}: sensitive prompt has label '{p['label']}'")
if p['label'] == 'DISALLOWED' and p['expected_behavior'] != 'REFUSE':
err(f"{p['id']}: DISALLOWED but expected_behavior='{p['expected_behavior']}'")
if p['label'] == 'SENSITIVE_ALLOWED' and p['expected_behavior'] == 'REFUSE':
err(f"{p['id']}: SENSITIVE_ALLOWED but expected_behavior='REFUSE'")
elif p['id'].startswith('NORMAL'):
if p['label'] != 'BENIGN':
err(f"{p['id']}: normal prompt has label '{p['label']}', expected BENIGN")
if p['expected_behavior'] != 'GENERATE':
err(f"{p['id']}: normal prompt has expected_behavior='{p['expected_behavior']}', expected GENERATE")
else:
err(f"{p['id']}: ID must start with SENSITIVE_ or NORMAL_")
# 7. Pair IDs
pair_members = {}
for p in all_prompts:
pid = p.get('pair_id')
if pid:
if not re.fullmatch(r'PAIR_\d{3}', pid):
err(f"{p['id']}: invalid pair_id format '{pid}'")
pair_members.setdefault(pid, []).append(p)
for pid, members in pair_members.items():
if len(members) != 2:
err(f"{pid}: has {len(members)} members, expected exactly 2")
continue
labels = sorted(m['label'] for m in members)
if labels != ['BENIGN', 'SENSITIVE_ALLOWED']:
err(f"{pid}: pair labels {labels}, expected one BENIGN + one SENSITIVE_ALLOWED")
if not any(m['id'].startswith('SENSITIVE') for m in members):
err(f"{pid}: missing SENSITIVE member")
if not any(m['id'].startswith('NORMAL') for m in members):
err(f"{pid}: missing NORMAL member")
print(f"OK: checked {len(pair_members)} pair groups")
# 8. No image outputs / no binary data
for p in all_prompts:
prompt = p['prompt']
if not isinstance(prompt, str) or not prompt.strip():
err(f"{p['id']}: empty or non-string prompt")
if '\x00' in prompt:
err(f"{p['id']}: prompt contains null byte")
if len(prompt) < 20:
warn(f"{p['id']}: unusually short prompt ({len(prompt)} chars)")
# 9. Categories.json cross-check
try:
with open('categories.json', encoding='utf-8') as f:
cats = json.load(f)
for cat in SENSITIVE_CATEGORIES:
if cat not in cats.get('sensitive', {}):
err(f"categories.json missing sensitive category '{cat}'")
for cat in NORMAL_CATEGORIES:
if cat not in cats.get('normal', {}):
err(f"categories.json missing normal category '{cat}'")
except FileNotFoundError:
warn("categories.json not found")
except json.JSONDecodeError as e:
err(f"categories.json invalid JSON: {e}")
# 10. Statistics cross-check
try:
with open('statistics.json', encoding='utf-8') as f:
stats = json.load(f)
if stats.get('total_prompts') != 200:
err(f"statistics.json total_prompts={stats.get('total_prompts')}, expected 200")
if stats.get('sensitive_count') != 100:
err(f"statistics.json sensitive_count={stats.get('sensitive_count')}, expected 100")
if stats.get('normal_count') != 100:
err(f"statistics.json normal_count={stats.get('normal_count')}, expected 100")
ld = stats.get('label_distribution', {})
actual_ld = Counter(p['label'] for p in all_prompts)
for label in VALID_LABELS:
if ld.get(label, 0) != actual_ld.get(label, 0):
err(f"statistics.json {label}={ld.get(label, 0)}, actual={actual_ld.get(label, 0)}")
except FileNotFoundError:
warn("statistics.json not found")
except json.JSONDecodeError as e:
err(f"statistics.json invalid JSON: {e}")
# Summary
print("\n" + "=" * 60)
print("VALIDATION SUMMARY")
print("=" * 60)
print(f"Total prompts: {len(all_prompts)}")
print(f"Sensitive prompts: {len(sensitive)}")
print(f"Normal prompts: {len(normal)}")
print(f"Unique prompts: {len(set(norm_prompts))}")
print(f"Matched pairs: {len(pair_members)}")
print(f"Labels: {dict(Counter(p['label'] for p in all_prompts))}")
print(f"Errors: {len(errors)}")
print(f"Warnings: {len(warnings)}")
if warnings:
print("\nWarnings:")
for w in warnings:
print(f" WARN: {w}")
if errors:
print("\nErrors:")
for e in errors:
print(f" ERROR: {e}")
print("\nRESULT: FAIL")
sys.exit(1)
else:
print("\nRESULT: PASS — dataset is valid.")
sys.exit(0)
|