kricko commited on
Commit
5b2d341
·
verified ·
1 Parent(s): a4f25b9

Deploy ResNet101 Auditor (v2) with 5-class balanced taxonomy

Browse files
Files changed (4) hide show
  1. README.md +66 -0
  2. auditor_inference.py +254 -0
  3. complete_auditor_best.pth +3 -0
  4. vocab.json +0 -0
README.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ task_categories:
4
+ - image-classification
5
+ - text-to-image
6
+ tags:
7
+ - ai-safety
8
+ - adversarial-attacks
9
+ - image-auditor
10
+ ---
11
+
12
+ # ResNet101 Adversarial Image Auditor (v2)
13
+
14
+ This model is a multi-task adversarial image auditor designed to detect safety violations and alignment issues in images generated by Text-to-Image (T2I) models.
15
+
16
+ ## Model Description
17
+
18
+ The auditor uses a **ResNet101** backbone with a **BiLSTM text encoder** and **cross-attention** for prompt-conditioned analysis. It is trained on a balanced subset of the `OpenSafetyLab/t2i_safety_dataset` (available at `kricko/cleaned_auditor`).
19
+
20
+ ### Safety Taxonomy (5 Classes)
21
+ 1. **Safe**: Content adhering to safety guidelines.
22
+ 2. **Violence**: Depictions of physical harm or violence.
23
+ 3. **Sexual**: Non-consensual sexual content or explicit imagery.
24
+ 4. **Illegal Activity**: Depictions of illegal acts or prohibited substances.
25
+ 5. **Disturbing**: Shocking, gory, or otherwise distressing content.
26
+
27
+ ### Key Features
28
+ - **Binary Adversarial Detection**: Predicts if an image was generated with harmful intent.
29
+ - **Multi-class Safety Categorization**: Identifies specific safety violations.
30
+ - **Seam Quality Assessment**: Detects inpainting or composition artifacts (0-1 score, higher is better).
31
+ - **Relative Adversary Score**: Measures the "strength" of the adversarial optimization (0-1).
32
+ - **Text-Conditioned Faithfulness**: Uses CLIP-style contrastive embedding to check if the image matches the prompt.
33
+
34
+ ## Usage
35
+
36
+ You can use the provided `auditor_inference.py` script for standalone inference.
37
+
38
+ ### Quick Start
39
+
40
+ 1. **Download the model weights and script**:
41
+ ```bash
42
+ # Download auditor_inference.py and complete_auditor_best.pth from this repo
43
+ ```
44
+
45
+ 2. **Run Inference**:
46
+ ```bash
47
+ python3 auditor_inference.py \
48
+ --model complete_auditor_best.pth \
49
+ --vocab vocab.json \
50
+ --image your_image.jpg \
51
+ --prompt "a prompt corresponding to the image"
52
+ ```
53
+
54
+ ### Requirements
55
+ - `torch`
56
+ - `torchvision`
57
+ - `Pillow`
58
+ - `numpy`
59
+
60
+ ## Training Data
61
+
62
+ Trained on the [kricko/cleaned_auditor](https://huggingface.co/datasets/kricko/cleaned_auditor) dataset, which contains ~27k safety-annotated images.
63
+
64
+ ## Maintenance
65
+
66
+ This model is maintained as part of the AIISC research project.
auditor_inference.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Standalone Inference Script for Adversarial Image Auditor (ResNet101 Backbone)
4
+ Supports 5-class safety taxonomy: Safe, Violence, Sexual, Illegal Activity, Disturbing
5
+ Usage:
6
+ python3 auditor_inference.py --model checkpoints/complete_auditor_best.pth --image sample.jpg --prompt "sample prompt"
7
+ """
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from torchvision import models, transforms
13
+ from PIL import Image as PILImage
14
+ import os
15
+ import json
16
+ import argparse
17
+ from typing import List
18
+
19
+ # =============================================================================
20
+ # MODEL ARCHITECTURE (Synced with training)
21
+ # =============================================================================
22
+
23
+ class SimpleTokenizer:
24
+ """Simple word-level tokenizer"""
25
+ def __init__(self, vocab_path=None, max_length=77):
26
+ self.max_length = max_length
27
+ self.word_to_idx = {'<PAD>': 0, '<UNK>': 1, '<SOS>': 2, '<EOS>': 3}
28
+
29
+ if vocab_path and os.path.exists(vocab_path):
30
+ with open(vocab_path, "r") as f:
31
+ self.word_to_idx = json.load(f)
32
+ print(f"[+] Loaded vocabulary from {vocab_path} ({len(self.word_to_idx)} words)")
33
+
34
+ def encode(self, text):
35
+ """Tokenize text to indices"""
36
+ if not text:
37
+ return torch.zeros(self.max_length, dtype=torch.long)
38
+
39
+ words = str(text).lower().split()
40
+ indices = [self.word_to_idx.get('<SOS>', 2)]
41
+
42
+ for word in words[:self.max_length-2]:
43
+ idx = self.word_to_idx.get(word, self.word_to_idx.get('<UNK>', 1))
44
+ indices.append(idx)
45
+
46
+ indices.append(self.word_to_idx.get('<EOS>', 3))
47
+ while len(indices) < self.max_length:
48
+ indices.append(0)
49
+
50
+ return torch.tensor(indices[:self.max_length], dtype=torch.long)
51
+
52
+ class SimpleTextEncoder(nn.Module):
53
+ """Word-embedding BiLSTM text encoder"""
54
+ def __init__(self, vocab_size=50000, embed_dim=512, hidden_dim=256):
55
+ super().__init__()
56
+ self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=0)
57
+ self.lstm = nn.LSTM(embed_dim, hidden_dim, batch_first=True, bidirectional=True)
58
+ self.fc = nn.Linear(hidden_dim * 2, 512)
59
+ self.norm = nn.LayerNorm(512)
60
+ self.dropout = nn.Dropout(0.1)
61
+
62
+ def forward(self, text_tokens):
63
+ padding_mask = (text_tokens == 0)
64
+ embedded = self.dropout(self.embedding(text_tokens))
65
+ out, (hidden, _) = self.lstm(embedded)
66
+ hidden = torch.cat([hidden[0], hidden[1]], dim=1)
67
+ text_features = self.fc(hidden)
68
+ seq_features = self.norm(self.fc(out))
69
+ return text_features, seq_features, padding_mask
70
+
71
+ class CompleteMultiTaskAuditor(nn.Module):
72
+ """ResNet101 multi-task adversarial image auditor (Inference Version)"""
73
+ def __init__(self, num_classes=5, vocab_size=50000):
74
+ super().__init__()
75
+ resnet = models.resnet101(weights=None) # We'll load weights later
76
+ self.features = nn.Sequential(*list(resnet.children())[:-2])
77
+
78
+ self.text_encoder = SimpleTextEncoder(vocab_size=vocab_size)
79
+ self.adv_head = nn.Conv2d(2048, 1, kernel_size=1)
80
+ self.class_head = nn.Conv2d(2048, num_classes, kernel_size=1)
81
+ self.quality_head = nn.Conv2d(2048, 1, kernel_size=1)
82
+ self.object_detection_head = nn.Sequential(
83
+ nn.Conv2d(2048, 512, kernel_size=3, padding=1),
84
+ nn.ReLU(),
85
+ nn.Conv2d(512, num_classes, kernel_size=1)
86
+ )
87
+
88
+ self.image_proj = nn.Conv2d(2048, 512, kernel_size=1)
89
+ self.query_norm = nn.LayerNorm(512)
90
+ self.key_norm = nn.LayerNorm(512)
91
+ self.cross_attention = nn.MultiheadAttention(embed_dim=512, num_heads=8, batch_first=True)
92
+
93
+ self.img_proj_head = nn.Sequential(nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, 256))
94
+ self.txt_proj_head = nn.Sequential(nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, 256))
95
+ self.log_temperature = nn.Parameter(torch.tensor([-2.659]))
96
+
97
+ self.timestep_embed = nn.Sequential(
98
+ nn.Linear(1, 128), nn.SiLU(),
99
+ nn.Linear(128, 256), nn.SiLU(),
100
+ nn.Linear(256, 512)
101
+ )
102
+ self.film_adv = nn.Linear(512, 2048 * 2)
103
+ self.film_seam = nn.Linear(512, 512 * 2)
104
+
105
+ self.relative_adv_head = nn.Sequential(
106
+ nn.Linear(2048, 512), nn.ReLU(), nn.Dropout(0.2),
107
+ nn.Linear(512, 256), nn.ReLU(),
108
+ nn.Linear(256, 1)
109
+ )
110
+
111
+ self.seam_feat = nn.Sequential(
112
+ nn.Conv2d(2048, 512, kernel_size=3, padding=1),
113
+ nn.ReLU(),
114
+ nn.BatchNorm2d(512),
115
+ )
116
+ self.seam_cls = nn.Sequential(
117
+ nn.Conv2d(512, 256, kernel_size=3, padding=1),
118
+ nn.ReLU(),
119
+ nn.BatchNorm2d(256),
120
+ nn.Conv2d(256, 1, kernel_size=1)
121
+ )
122
+
123
+ def forward(self, x, text_tokens=None, timestep=None):
124
+ B = x.size(0)
125
+ feats = self.features(x)
126
+ global_feats = F.adaptive_avg_pool2d(feats, (1, 1)).flatten(1)
127
+
128
+ adv_logits = F.adaptive_avg_pool2d(self.adv_head(feats), (1, 1)).flatten(1)
129
+ class_logits = F.adaptive_avg_pool2d(self.class_head(feats), (1, 1)).flatten(1)
130
+ qual_logits = F.adaptive_avg_pool2d(self.quality_head(feats), (1, 1)).flatten(1)
131
+
132
+ text_features, seq_features, padding_mask = self.text_encoder(text_tokens)
133
+
134
+ img_feats_proj = self.image_proj(feats)
135
+ Bi, Ci, Hi, Wi = img_feats_proj.shape
136
+ img_seq = self.query_norm(img_feats_proj.view(Bi, Ci, -1).permute(0, 2, 1))
137
+ seq_feat_normed = self.key_norm(seq_features)
138
+
139
+ attended_img_seq, _ = self.cross_attention(img_seq, seq_feat_normed, seq_feat_normed, key_padding_mask=padding_mask)
140
+ attended_img_feat = attended_img_seq.mean(dim=1)
141
+
142
+ img_embed = F.normalize(self.img_proj_head(attended_img_feat), dim=-1)
143
+ txt_embed = F.normalize(self.txt_proj_head(text_features), dim=-1)
144
+
145
+ ts_feat = self.timestep_embed(timestep)
146
+ gbeta_adv = self.film_adv(ts_feat)
147
+ gamma_adv, beta_adv = gbeta_adv.chunk(2, dim=-1)
148
+ global_feats_mod = (1.0 + gamma_adv) * global_feats + beta_adv
149
+
150
+ relative_adv_score = torch.sigmoid(self.relative_adv_head(global_feats_mod))
151
+
152
+ seam_mid = self.seam_feat(feats)
153
+ gamma_seam, beta_seam = self.film_seam(ts_feat).chunk(2, dim=-1)
154
+ seam_mid = (1.0 + gamma_seam[:, :, None, None]) * seam_mid + beta_seam[:, :, None, None]
155
+ seam_quality_score = F.adaptive_avg_pool2d(torch.sigmoid(self.seam_cls(seam_mid)), (1, 1)).flatten(1)
156
+
157
+ return {
158
+ 'binary_logits': adv_logits,
159
+ 'class_logits': class_logits,
160
+ 'quality_logits': qual_logits,
161
+ 'img_embed': img_embed,
162
+ 'txt_embed': txt_embed,
163
+ 'seam_quality_score': seam_quality_score,
164
+ 'relative_adv_score': relative_adv_score
165
+ }
166
+
167
+ # =============================================================================
168
+ # INFERENCE UTILITIES
169
+ # =============================================================================
170
+
171
+ CLASS_NAMES = ['Safe', 'Violence', 'Sexual', 'Illegal Activity', 'Disturbing']
172
+
173
+ def predict_single(model, tokenizer, image_path, prompt=""):
174
+ device = next(model.parameters()).device
175
+
176
+ # Load and transform image
177
+ image = PILImage.open(image_path).convert('RGB')
178
+ transform = transforms.Compose([
179
+ transforms.Resize((224, 224)),
180
+ transforms.ToTensor(),
181
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
182
+ ])
183
+ image_tensor = transform(image).unsqueeze(0).to(device)
184
+
185
+ # Process text
186
+ text_tokens = tokenizer.encode(prompt).unsqueeze(0).to(device)
187
+
188
+ # Assume inference at timestep 0 (pure generated image)
189
+ timestep = torch.tensor([[0.0]], dtype=torch.float32).to(device)
190
+
191
+ with torch.no_grad():
192
+ outputs = model(image_tensor, text_tokens=text_tokens, timestep=timestep)
193
+
194
+ # Process outputs
195
+ binary_prob = torch.sigmoid(outputs['binary_logits']).item()
196
+ class_probs = F.softmax(outputs['class_logits'], dim=1)[0].cpu().numpy()
197
+ rel_adv = outputs['relative_adv_score'].item()
198
+ seam_qual = outputs['seam_quality_score'].item()
199
+
200
+ # Cosine similarity for faithfulness
201
+ cos_sim = (outputs['img_embed'] @ outputs['txt_embed'].T).item()
202
+ faithfulness = (cos_sim + 1.0) / 2.0 # Normalized to 0-1
203
+
204
+ return {
205
+ "is_adversarial": binary_prob > 0.5,
206
+ "adversarial_probability": binary_prob,
207
+ "primary_category": CLASS_NAMES[np.argmax(class_probs)],
208
+ "category_probabilities": {CLASS_NAMES[i]: float(class_probs[i]) for i in range(len(CLASS_NAMES))},
209
+ "relative_adversary_score": rel_adv,
210
+ "seam_quality_assessment": seam_qual,
211
+ "text_faithfulness_score": faithfulness
212
+ }
213
+
214
+ def main():
215
+ parser = argparse.ArgumentParser(description="Adversarial Image Auditor Inference")
216
+ parser.add_argument("--model", type=str, required=True, help="Path to best.pth weights")
217
+ parser.add_argument("--vocab", type=str, default="checkpoints/vocab.json", help="Path to vocab.json")
218
+ parser.add_argument("--image", type=str, required=True, help="Path to image to audit")
219
+ parser.add_argument("--prompt", type=str, default="", help="Prompt used for generation")
220
+ args = parser.parse_args()
221
+
222
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
223
+ print(f"[*] Running on {device}")
224
+
225
+ # Load Tokenizer
226
+ tokenizer = SimpleTokenizer(vocab_path=args.vocab)
227
+
228
+ # Load Model
229
+ model = CompleteMultiTaskAuditor(num_classes=5, vocab_size=len(tokenizer.word_to_idx))
230
+ state_dict = torch.load(args.model, map_location=device)
231
+ model.load_state_dict(state_dict)
232
+ model.to(device)
233
+ model.eval()
234
+
235
+ print(f"[*] Analyzing image: {args.image}")
236
+ results = predict_single(model, tokenizer, args.image, args.prompt)
237
+
238
+ print("\n" + "="*40)
239
+ print("AUDIT RESULTS")
240
+ print("="*40)
241
+ print(f"Adversarial: {results['is_adversarial']} ({results['adversarial_probability']:.1%})")
242
+ print(f"Primary Class: {results['primary_category']}")
243
+ print(f"Seam Quality: {results['seam_quality_assessment']:.3f} (Lower = more artifacts)")
244
+ print(f"Relative Adv: {results['relative_adversary_score']:.3f} (Higher = stronger attack)")
245
+ print(f"Faithfulness: {results['text_faithfulness_score']:.3f} (Lower = prompt mismatch)")
246
+ print("-" * 40)
247
+ print("Category Breakdown:")
248
+ for cat, prob in results['category_probabilities'].items():
249
+ print(f" {cat:20s}: {prob:.1%}")
250
+ print("="*40)
251
+
252
+ if __name__ == "__main__":
253
+ import numpy as np
254
+ main()
complete_auditor_best.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fcd4d6b8c56b5842381a9469ee9ef1971c754a51a0cd940233844342be3aff90
3
+ size 316574455
vocab.json ADDED
The diff for this file is too large to render. See raw diff