kricko commited on
Commit
06caeed
·
verified ·
1 Parent(s): a431b53

Clear repo for new ResNet101 auditor deployment

Browse files
Files changed (4) hide show
  1. README.md +0 -74
  2. auditor_inference.py +0 -305
  3. complete_auditor_best.pth +0 -3
  4. vocab.json +0 -0
README.md DELETED
@@ -1,74 +0,0 @@
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
- - **Visual Safety Heatmaps**: Generates heatmaps highlighting regions that triggered safety violations (available via `return_heatmaps=True`).
31
- - **Seam Quality Assessment**: Detects inpainting or composition artifacts (0-1 score, higher is better).
32
- - **Relative Adversary Score**: Measures the "strength" of the adversarial optimization.
33
- - **Text-Conditioned Faithfulness**: Checks if the image matches the prompt using CLIP-style embeddings.
34
-
35
- ## Usage
36
-
37
- You can use the provided `auditor_inference.py` script for standalone inference with visual explanations.
38
-
39
- ### Quick Start
40
-
41
- 1. **Run Inference with Heatmaps**:
42
- ```bash
43
- python3 auditor_inference.py \
44
- --model complete_auditor_best.pth \
45
- --vocab vocab.json \
46
- --image your_image.jpg \
47
- --prompt "a prompt corresponding to the image"
48
- ```
49
- *This will save `your_image_adv_heatmap.jpg` and class-specific heatmaps to your current directory.*
50
-
51
- ### Programmatic Usage
52
- ```python
53
- from auditor_inference import audit_image
54
-
55
- results = audit_image(
56
- model_path="complete_auditor_best.pth",
57
- image_path="sample.jpg",
58
- prompt="a sample prompt",
59
- return_heatmaps=True
60
- )
61
-
62
- print(results["is_adversarial"])
63
- # Heatmaps are available as numpy arrays (original image size)
64
- # results["adversarial_heatmap"]
65
- # results["category_heatmaps"]["Violence"]
66
- ```
67
-
68
- ## Training Data
69
-
70
- Trained on the [kricko/cleaned_auditor](https://huggingface.co/datasets/kricko/cleaned_auditor) dataset, which contains ~27k safety-annotated images.
71
-
72
- ## Maintenance
73
-
74
- This model is maintained as part of the AIISC research project.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
auditor_inference.py DELETED
@@ -1,305 +0,0 @@
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, return_features=False):
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
- out = {
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
- if return_features:
168
- out['adversarial_map'] = torch.sigmoid(self.adv_head(feats))
169
- out['object_heatmaps'] = torch.sigmoid(self.object_detection_head(feats))
170
-
171
- return out
172
-
173
- # =============================================================================
174
- # INFERENCE UTILITIES
175
- # =============================================================================
176
-
177
- CLASS_NAMES = ['Safe', 'Violence', 'Sexual', 'Illegal Activity', 'Disturbing']
178
-
179
- def predict_single(model, tokenizer, image_path, prompt="", return_heatmaps=False):
180
- device = next(model.parameters()).device
181
-
182
- # Load and transform image
183
- image = PILImage.open(image_path).convert('RGB')
184
- orig_w, orig_h = image.size
185
- transform = transforms.Compose([
186
- transforms.Resize((224, 224)),
187
- transforms.ToTensor(),
188
- transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
189
- ])
190
- image_tensor = transform(image).unsqueeze(0).to(device)
191
-
192
- # Process text
193
- text_tokens = tokenizer.encode(prompt).unsqueeze(0).to(device)
194
-
195
- # Assume inference at timestep 0 (pure generated image)
196
- timestep = torch.tensor([[0.0]], dtype=torch.float32).to(device)
197
-
198
- with torch.no_grad():
199
- outputs = model(image_tensor, text_tokens=text_tokens, timestep=timestep, return_features=return_heatmaps)
200
-
201
- # Process outputs
202
- binary_prob = torch.sigmoid(outputs['binary_logits']).item()
203
- class_probs = F.softmax(outputs['class_logits'], dim=1)[0].cpu().numpy()
204
- rel_adv = outputs['relative_adv_score'].item()
205
- seam_qual = outputs['seam_quality_score'].item()
206
-
207
- # Cosine similarity for faithfulness
208
- cos_sim = (outputs['img_embed'] @ outputs['txt_embed'].T).item()
209
- faithfulness = (cos_sim + 1.0) / 2.0 # Normalized to 0-1
210
-
211
- res = {
212
- "is_adversarial": binary_prob > 0.5,
213
- "adversarial_probability": binary_prob,
214
- "primary_category": CLASS_NAMES[np.argmax(class_probs)],
215
- "category_probabilities": {CLASS_NAMES[i]: float(class_probs[i]) for i in range(len(CLASS_NAMES))},
216
- "relative_adversary_score": rel_adv,
217
- "seam_quality_assessment": seam_qual,
218
- "text_faithfulness_score": faithfulness
219
- }
220
-
221
- if return_heatmaps:
222
- # Resize heatmaps to original image size
223
- adv_map = F.interpolate(outputs['adversarial_map'], size=(orig_h, orig_w), mode='bilinear', align_corners=False)
224
- obj_maps = F.interpolate(outputs['object_heatmaps'], size=(orig_h, orig_w), mode='bilinear', align_corners=False)
225
-
226
- res['adversarial_heatmap'] = adv_map[0, 0].cpu().numpy()
227
- res['category_heatmaps'] = {CLASS_NAMES[i]: obj_maps[0, i].cpu().numpy() for i in range(len(CLASS_NAMES))}
228
-
229
- return res
230
-
231
- def audit_image(model_path, image_path, prompt="", vocab_path="checkpoints/vocab.json", return_heatmaps=False):
232
- """Convenience wrapper for auditing an image"""
233
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
234
- tokenizer = SimpleTokenizer(vocab_path=vocab_path)
235
- model = CompleteMultiTaskAuditor(num_classes=5, vocab_size=len(tokenizer.word_to_idx))
236
- model.load_state_dict(torch.load(model_path, map_location=device))
237
- model.to(device).eval()
238
- return predict_single(model, tokenizer, image_path, prompt, return_heatmaps=return_heatmaps)
239
-
240
- def main():
241
- parser = argparse.ArgumentParser(description="Adversarial Image Auditor Inference")
242
- parser.add_argument("--model", type=str, required=True, help="Path to best.pth weights")
243
- parser.add_argument("--vocab", type=str, default="checkpoints/vocab.json", help="Path to vocab.json")
244
- parser.add_argument("--image", type=str, required=True, help="Path to image to audit")
245
- parser.add_argument("--prompt", type=str, default="", help="Prompt used for generation")
246
- args = parser.parse_args()
247
-
248
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
249
- print(f"[*] Running on {device}")
250
-
251
- # Load Tokenizer
252
- tokenizer = SimpleTokenizer(vocab_path=args.vocab)
253
-
254
- # Load Model
255
- model = CompleteMultiTaskAuditor(num_classes=5, vocab_size=len(tokenizer.word_to_idx))
256
- state_dict = torch.load(args.model, map_location=device)
257
- model.load_state_dict(state_dict)
258
- model.to(device)
259
- model.eval()
260
-
261
- print(f"[*] Analyzing image: {args.image}")
262
- results = predict_single(model, tokenizer, args.image, args.prompt, return_heatmaps=True)
263
-
264
- print("\n" + "="*40)
265
- print("AUDIT RESULTS")
266
- print("="*40)
267
- print(f"Adversarial: {results['is_adversarial']} ({results['adversarial_probability']:.1%})")
268
- print(f"Primary Class: {results['primary_category']}")
269
- print(f"Seam Quality: {results['seam_quality_assessment']:.3f}")
270
- print(f"Relative Adv: {results['relative_adversary_score']:.3f}")
271
- print(f"Faithfulness: {results['text_faithfulness_score']:.3f}")
272
- print("-" * 40)
273
- print("Category Breakdown:")
274
- for cat, prob in results['category_probabilities'].items():
275
- print(f" {cat:20s}: {prob:.1%}")
276
-
277
- # Save Heatmaps
278
- import cv2
279
- output_base = os.path.splitext(os.path.basename(args.image))[0]
280
- orig_img = cv2.imread(args.image)
281
-
282
- # Save Adversarial Heatmap
283
- if 'adversarial_heatmap' in results:
284
- h_map = (results['adversarial_heatmap'] * 255).astype(np.uint8)
285
- heatmap_img = cv2.applyColorMap(h_map, cv2.COLORMAP_JET)
286
- blended = cv2.addWeighted(orig_img, 0.6, heatmap_img, 0.4, 0)
287
- out_name = f"{output_base}_adv_heatmap.jpg"
288
- cv2.imwrite(out_name, blended)
289
- print(f"[*] Saved adversarial heatmap to {out_name}")
290
-
291
- # Save Primary Class Heatmap
292
- primary = results['primary_category']
293
- if 'category_heatmaps' in results and primary in results['category_heatmaps']:
294
- h_map = (results['category_heatmaps'][primary] * 255).astype(np.uint8)
295
- heatmap_img = cv2.applyColorMap(h_map, cv2.COLORMAP_JET)
296
- blended = cv2.addWeighted(orig_img, 0.6, heatmap_img, 0.4, 0)
297
- out_name = f"{output_base}_{primary.lower()}_heatmap.jpg"
298
- cv2.imwrite(out_name, blended)
299
- print(f"[*] Saved category heatmap to {out_name}")
300
-
301
- print("="*40)
302
-
303
- if __name__ == "__main__":
304
- import numpy as np
305
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
complete_auditor_best.pth DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:fcd4d6b8c56b5842381a9469ee9ef1971c754a51a0cd940233844342be3aff90
3
- size 316574455
 
 
 
 
vocab.json DELETED
The diff for this file is too large to render. See raw diff