feat: primeira versão
Browse files- app.py +560 -0
- requirements.txt +9 -0
- utils/attacks.py +130 -0
- utils/inference.py +27 -0
- utils/model_loader.py +153 -0
- utils/preprocessing.py +31 -0
- utils/visualization.py +256 -0
app.py
ADDED
|
@@ -0,0 +1,560 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from typing import Optional, List, Tuple
|
| 5 |
+
|
| 6 |
+
from utils.model_loader import load_model_and_labels
|
| 7 |
+
from utils.preprocessing import get_default_transform, preprocess_image
|
| 8 |
+
from utils.inference import predict_topk
|
| 9 |
+
from utils.attacks import PGDIterations
|
| 10 |
+
from utils.visualization import extract_attention_maps, attention_rollout, create_attention_overlay, extract_attention_for_iterations, create_iteration_attention_overlays
|
| 11 |
+
|
| 12 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 13 |
+
|
| 14 |
+
transform = get_default_transform()
|
| 15 |
+
|
| 16 |
+
def _to_path(file_like: Optional[object]) -> Optional[str]:
|
| 17 |
+
"""Extrai caminho de um objeto vindo do Gradio File (string, dict com 'name' ou objeto com atributo .name)."""
|
| 18 |
+
if file_like is None:
|
| 19 |
+
return None
|
| 20 |
+
if isinstance(file_like, str):
|
| 21 |
+
return file_like
|
| 22 |
+
# dict do gradio {'name': '/tmp/xxx', ...}
|
| 23 |
+
if isinstance(file_like, dict) and 'name' in file_like:
|
| 24 |
+
return file_like['name']
|
| 25 |
+
# objetos com .name
|
| 26 |
+
path = getattr(file_like, 'name', None)
|
| 27 |
+
if isinstance(path, str):
|
| 28 |
+
return path
|
| 29 |
+
return None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def classify_image(model_file, image, labels_file=None):
|
| 33 |
+
"""
|
| 34 |
+
Carrega o modelo e classifica a imagem
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
model_file: caminho para o arquivo .pth do modelo (pode ser state_dict ou modelo completo)
|
| 38 |
+
image: imagem PIL ou caminho para a imagem
|
| 39 |
+
labels_file: arquivo opcional com nomes das classes (.txt ou .json)
|
| 40 |
+
|
| 41 |
+
Returns:
|
| 42 |
+
str: label de classificação
|
| 43 |
+
"""
|
| 44 |
+
try:
|
| 45 |
+
if model_file is None:
|
| 46 |
+
return "Por favor, envie um arquivo de modelo (.pth)"
|
| 47 |
+
# Extrair paths dos componentes de arquivo do Gradio
|
| 48 |
+
model_path = _to_path(model_file)
|
| 49 |
+
labels_path = _to_path(labels_file)
|
| 50 |
+
|
| 51 |
+
# Carregar modelo e labels
|
| 52 |
+
model, class_names, label_source = load_model_and_labels(model_path, labels_path, device=DEVICE)
|
| 53 |
+
|
| 54 |
+
# Processar imagem
|
| 55 |
+
if not (isinstance(image, str) or isinstance(image, Image.Image)):
|
| 56 |
+
return "Por favor, envie uma imagem válida"
|
| 57 |
+
|
| 58 |
+
img_tensor = preprocess_image(image, transform=transform).to(DEVICE)
|
| 59 |
+
|
| 60 |
+
# Inferência
|
| 61 |
+
top_prob, top_idx, num_classes, probabilities = predict_topk(model, img_tensor, top_k=5, device=DEVICE)
|
| 62 |
+
|
| 63 |
+
top_k = len(top_prob)
|
| 64 |
+
result = f"**Top {top_k} Predições:**\n\n"
|
| 65 |
+
result += f"**Modelo:** {num_classes} classes detectadas\n"
|
| 66 |
+
|
| 67 |
+
# Indicar origem dos labels
|
| 68 |
+
if class_names:
|
| 69 |
+
if label_source == 'file':
|
| 70 |
+
result += f"**Labels:** Carregados do arquivo\n\n"
|
| 71 |
+
else:
|
| 72 |
+
result += f"**Labels:** Encontrados no checkpoint\n\n"
|
| 73 |
+
else:
|
| 74 |
+
result += f"**Labels:** Não disponíveis (mostrando índices)\n\n"
|
| 75 |
+
|
| 76 |
+
for i, (prob, idx) in enumerate(zip(top_prob, top_idx)):
|
| 77 |
+
class_idx = idx.item()
|
| 78 |
+
if class_names and class_idx in class_names:
|
| 79 |
+
class_label = class_names[class_idx]
|
| 80 |
+
result += f"{i+1}. **{class_label}** (classe {class_idx}): {prob.item()*100:.2f}%\n"
|
| 81 |
+
else:
|
| 82 |
+
result += f"{i+1}. **Classe {class_idx}**: {prob.item()*100:.2f}%\n"
|
| 83 |
+
|
| 84 |
+
return result
|
| 85 |
+
|
| 86 |
+
except Exception as e:
|
| 87 |
+
import traceback
|
| 88 |
+
return f"❌ Erro ao processar modelo:\n```\n{str(e)}\n\n{traceback.format_exc()}\n```"
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def visualize_attention(
|
| 92 |
+
model_file,
|
| 93 |
+
image,
|
| 94 |
+
labels_file,
|
| 95 |
+
discard_ratio: float,
|
| 96 |
+
head_fusion: str,
|
| 97 |
+
alpha_overlay: float
|
| 98 |
+
) -> Tuple[Image.Image, str]:
|
| 99 |
+
"""
|
| 100 |
+
Visualiza o mapa de atenção do modelo usando Attention Rollout.
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
model_file: arquivo .pth do modelo
|
| 104 |
+
image: imagem PIL
|
| 105 |
+
labels_file: arquivo opcional de labels
|
| 106 |
+
discard_ratio: proporção de atenções fracas a descartar
|
| 107 |
+
head_fusion: como agregar heads ('mean', 'max', 'min')
|
| 108 |
+
alpha_overlay: transparência da sobreposição
|
| 109 |
+
|
| 110 |
+
Returns:
|
| 111 |
+
(attention_overlay_image, result_text)
|
| 112 |
+
"""
|
| 113 |
+
try:
|
| 114 |
+
if model_file is None:
|
| 115 |
+
return None, "Por favor, envie um arquivo de modelo (.pth)"
|
| 116 |
+
if image is None:
|
| 117 |
+
return None, "Por favor, envie uma imagem"
|
| 118 |
+
|
| 119 |
+
# Carregar modelo e labels
|
| 120 |
+
model_path = _to_path(model_file)
|
| 121 |
+
labels_path = _to_path(labels_file)
|
| 122 |
+
model, class_names, label_source = load_model_and_labels(model_path, labels_path, device=DEVICE)
|
| 123 |
+
|
| 124 |
+
# Processar imagem
|
| 125 |
+
img_tensor = preprocess_image(image, transform=transform).to(DEVICE)
|
| 126 |
+
|
| 127 |
+
# Predição
|
| 128 |
+
top_prob, top_idx, num_classes, _ = predict_topk(model, img_tensor, top_k=1, device=DEVICE)
|
| 129 |
+
pred_class = top_idx[0].item()
|
| 130 |
+
pred_prob = top_prob[0].item()
|
| 131 |
+
|
| 132 |
+
# Extrair mapas de atenção (retorna lista, não dict)
|
| 133 |
+
attentions = extract_attention_maps(model, img_tensor)
|
| 134 |
+
|
| 135 |
+
# Aplicar Attention Rollout
|
| 136 |
+
attention_mask = attention_rollout(
|
| 137 |
+
attentions,
|
| 138 |
+
discard_ratio=discard_ratio,
|
| 139 |
+
head_fusion=head_fusion
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
# Criar overlay
|
| 143 |
+
attention_overlay = create_attention_overlay(
|
| 144 |
+
image,
|
| 145 |
+
attention_mask,
|
| 146 |
+
alpha=alpha_overlay,
|
| 147 |
+
colormap='jet'
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
# Formatar resultado
|
| 151 |
+
result = "## 🔍 Visualização de Atenção (Attention Rollout)\n\n"
|
| 152 |
+
result += f"**Predição do Modelo:**\n"
|
| 153 |
+
if class_names and pred_class in class_names:
|
| 154 |
+
result += f"- Classe: **{class_names[pred_class]}** (índice {pred_class})\n"
|
| 155 |
+
else:
|
| 156 |
+
result += f"- Classe: **{pred_class}**\n"
|
| 157 |
+
result += f"- Confiança: {pred_prob*100:.2f}%\n\n"
|
| 158 |
+
|
| 159 |
+
result += f"**Configuração da Visualização:**\n"
|
| 160 |
+
result += f"- Head Fusion: {head_fusion}\n"
|
| 161 |
+
result += f"- Discard Ratio: {discard_ratio:.1%}\n"
|
| 162 |
+
result += f"- Transparência: {alpha_overlay:.2f}\n\n"
|
| 163 |
+
|
| 164 |
+
result += "**Interpretação:**\n"
|
| 165 |
+
result += "As regiões em vermelho/amarelo indicam onde o modelo está 'olhando' para fazer a classificação.\n"
|
| 166 |
+
|
| 167 |
+
return attention_overlay, result
|
| 168 |
+
|
| 169 |
+
except Exception as e:
|
| 170 |
+
import traceback
|
| 171 |
+
error_msg = f"❌ Erro ao visualizar atenção:\n```\n{str(e)}\n\n{traceback.format_exc()}\n```"
|
| 172 |
+
return None, error_msg
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def run_pgd_attack(
|
| 176 |
+
model_file,
|
| 177 |
+
image,
|
| 178 |
+
labels_file,
|
| 179 |
+
eps: float,
|
| 180 |
+
alpha: float,
|
| 181 |
+
steps: int,
|
| 182 |
+
discard_ratio: float,
|
| 183 |
+
head_fusion: str,
|
| 184 |
+
alpha_overlay: float
|
| 185 |
+
) -> Tuple[List[Image.Image], str, Image.Image, List[Image.Image]]:
|
| 186 |
+
"""
|
| 187 |
+
Executa ataque PGD untargeted e extrai atenção de cada iteração.
|
| 188 |
+
|
| 189 |
+
Args:
|
| 190 |
+
model_file: arquivo .pth do modelo
|
| 191 |
+
image: imagem PIL
|
| 192 |
+
labels_file: arquivo opcional de labels
|
| 193 |
+
eps: epsilon (perturbação máxima)
|
| 194 |
+
alpha: step size
|
| 195 |
+
steps: número de iterações
|
| 196 |
+
discard_ratio: proporção de atenções fracas a descartar
|
| 197 |
+
head_fusion: como agregar heads ('mean', 'max', 'min')
|
| 198 |
+
alpha_overlay: transparência da sobreposição
|
| 199 |
+
|
| 200 |
+
Returns:
|
| 201 |
+
(iteration_images, result_text, final_adv_image, attention_overlays)
|
| 202 |
+
"""
|
| 203 |
+
try:
|
| 204 |
+
if model_file is None:
|
| 205 |
+
return [], "Por favor, envie um arquivo de modelo (.pth)", None, []
|
| 206 |
+
if image is None:
|
| 207 |
+
return [], "Por favor, envie uma imagem", None, []
|
| 208 |
+
|
| 209 |
+
# Carregar modelo e labels
|
| 210 |
+
model_path = _to_path(model_file)
|
| 211 |
+
labels_path = _to_path(labels_file)
|
| 212 |
+
model, class_names, label_source = load_model_and_labels(model_path, labels_path, device=DEVICE)
|
| 213 |
+
|
| 214 |
+
# Processar imagem
|
| 215 |
+
img_tensor = preprocess_image(image, transform=transform).to(DEVICE)
|
| 216 |
+
|
| 217 |
+
# Predição original
|
| 218 |
+
top_prob_orig, top_idx_orig, num_classes, _ = predict_topk(model, img_tensor, top_k=1, device=DEVICE)
|
| 219 |
+
orig_class = top_idx_orig[0].item()
|
| 220 |
+
orig_prob = top_prob_orig[0].item()
|
| 221 |
+
|
| 222 |
+
# Configurar ataque PGD untargeted
|
| 223 |
+
attack = PGDIterations(model, eps=eps, alpha=alpha, steps=steps)
|
| 224 |
+
|
| 225 |
+
# Para untargeted, usamos a classe original como "label verdadeiro"
|
| 226 |
+
# O PGD maximizará a loss para essa classe (fazendo o modelo errar)
|
| 227 |
+
original_label = torch.tensor([orig_class], device=DEVICE)
|
| 228 |
+
|
| 229 |
+
# Executar ataque
|
| 230 |
+
adv_tensor, iteration_images = attack(img_tensor, original_label)
|
| 231 |
+
|
| 232 |
+
# Extrair atenção para todas as iterações (incluindo original)
|
| 233 |
+
attention_masks = extract_attention_for_iterations(
|
| 234 |
+
model,
|
| 235 |
+
attack.iteration_tensors,
|
| 236 |
+
discard_ratio=discard_ratio,
|
| 237 |
+
head_fusion=head_fusion
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
# Criar overlays de atenção
|
| 241 |
+
attention_overlays = create_iteration_attention_overlays(
|
| 242 |
+
iteration_images,
|
| 243 |
+
attention_masks,
|
| 244 |
+
alpha=alpha_overlay
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
# Predição adversarial
|
| 248 |
+
top_prob_adv, top_idx_adv, _, _ = predict_topk(model, adv_tensor, top_k=1, device=DEVICE)
|
| 249 |
+
adv_class = top_idx_adv[0].item()
|
| 250 |
+
adv_prob = top_prob_adv[0].item()
|
| 251 |
+
|
| 252 |
+
# Converter imagem adversarial final para PIL
|
| 253 |
+
from utils.attacks import tensor_to_pil
|
| 254 |
+
final_adv_image = tensor_to_pil(adv_tensor[0])
|
| 255 |
+
|
| 256 |
+
# Formatar resultado
|
| 257 |
+
result = "## 🎯 Resultado do Ataque PGD (Untargeted)\n\n"
|
| 258 |
+
result += f"**Configuração:**\n"
|
| 259 |
+
result += f"- Tipo: Untargeted (objetivo: fazer o modelo errar)\n"
|
| 260 |
+
result += f"- Epsilon (ε): {eps:.4f}\n"
|
| 261 |
+
result += f"- Alpha (α): {alpha:.4f}\n"
|
| 262 |
+
result += f"- Steps: {steps}\n\n"
|
| 263 |
+
|
| 264 |
+
result += f"**Predição Original:**\n"
|
| 265 |
+
if class_names and orig_class in class_names:
|
| 266 |
+
result += f"- Classe: **{class_names[orig_class]}** (índice {orig_class})\n"
|
| 267 |
+
else:
|
| 268 |
+
result += f"- Classe: **{orig_class}**\n"
|
| 269 |
+
result += f"- Confiança: {orig_prob*100:.2f}%\n\n"
|
| 270 |
+
|
| 271 |
+
result += f"**Predição Adversarial:**\n"
|
| 272 |
+
if class_names and adv_class in class_names:
|
| 273 |
+
result += f"- Classe: **{class_names[adv_class]}** (índice {adv_class})\n"
|
| 274 |
+
else:
|
| 275 |
+
result += f"- Classe: **{adv_class}**\n"
|
| 276 |
+
result += f"- Confiança: {adv_prob*100:.2f}%\n\n"
|
| 277 |
+
|
| 278 |
+
if adv_class != orig_class:
|
| 279 |
+
result += "✅ **Ataque bem-sucedido!** Modelo mudou a predição.\n\n"
|
| 280 |
+
else:
|
| 281 |
+
result += "⚠️ **Ataque falhou.** Modelo manteve a mesma predição.\n\n"
|
| 282 |
+
|
| 283 |
+
result += f"**Visualização de Atenção:**\n"
|
| 284 |
+
result += f"- Total de iterações capturadas: {len(attention_overlays)}\n"
|
| 285 |
+
result += f"- Use o slider abaixo para explorar como a atenção evolui durante o ataque\n"
|
| 286 |
+
result += f"- Iteração 0 = Imagem original\n"
|
| 287 |
+
result += f"- Iteração {steps} = Imagem adversarial final\n"
|
| 288 |
+
|
| 289 |
+
return iteration_images, result, final_adv_image, attention_overlays
|
| 290 |
+
|
| 291 |
+
except Exception as e:
|
| 292 |
+
import traceback
|
| 293 |
+
error_msg = f"❌ Erro ao executar ataque:\n```\n{str(e)}\n\n{traceback.format_exc()}\n```"
|
| 294 |
+
return [], error_msg, None, []
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def create_app():
|
| 298 |
+
"""Cria interface Gradio"""
|
| 299 |
+
|
| 300 |
+
with gr.Blocks(title="ViTViz - Classifier & Attacks", theme=gr.themes.Soft()) as app:
|
| 301 |
+
gr.Markdown("""
|
| 302 |
+
# 🔍 ViTViz: Vision Transformer Classifier & Adversarial Attacks
|
| 303 |
+
""")
|
| 304 |
+
|
| 305 |
+
with gr.Tabs():
|
| 306 |
+
# Tab 1: Classificação simples
|
| 307 |
+
with gr.Tab("📊 Classificação"):
|
| 308 |
+
gr.Markdown("### Upload um modelo e uma imagem para classificação")
|
| 309 |
+
|
| 310 |
+
with gr.Row():
|
| 311 |
+
with gr.Column():
|
| 312 |
+
model_upload_classify = gr.File(
|
| 313 |
+
label="Upload Model (.pth/.pt)",
|
| 314 |
+
file_types=[".pth", ".pt"]
|
| 315 |
+
)
|
| 316 |
+
labels_upload_classify = gr.File(
|
| 317 |
+
label="Upload Class Labels (opcional - .txt/.json)",
|
| 318 |
+
file_types=[".txt", ".json"]
|
| 319 |
+
)
|
| 320 |
+
image_upload_classify = gr.Image(
|
| 321 |
+
label="Upload Image",
|
| 322 |
+
type="pil"
|
| 323 |
+
)
|
| 324 |
+
classify_btn = gr.Button("🚀 Classificar", variant="primary")
|
| 325 |
+
|
| 326 |
+
with gr.Column():
|
| 327 |
+
output_text_classify = gr.Markdown(label="Resultado")
|
| 328 |
+
|
| 329 |
+
# Event: classificar imagem
|
| 330 |
+
classify_btn.click(
|
| 331 |
+
fn=classify_image,
|
| 332 |
+
inputs=[model_upload_classify, image_upload_classify, labels_upload_classify],
|
| 333 |
+
outputs=[output_text_classify]
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
# Tab 2: Ataque adversarial
|
| 337 |
+
with gr.Tab("⚔️ Adversarial Attack + Attention"):
|
| 338 |
+
gr.Markdown("### Execute ataques adversariais e visualize como a atenção evolui")
|
| 339 |
+
|
| 340 |
+
with gr.Row():
|
| 341 |
+
with gr.Column(scale=1):
|
| 342 |
+
model_upload_attack = gr.File(
|
| 343 |
+
label="Upload Model (.pth/.pt)",
|
| 344 |
+
file_types=[".pth", ".pt"]
|
| 345 |
+
)
|
| 346 |
+
labels_upload_attack = gr.File(
|
| 347 |
+
label="Upload Class Labels (opcional - .txt/.json)",
|
| 348 |
+
file_types=[".txt", ".json"]
|
| 349 |
+
)
|
| 350 |
+
image_upload_attack = gr.Image(
|
| 351 |
+
label="Upload Image",
|
| 352 |
+
type="pil"
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
gr.Markdown("#### ⚔️ Configuração do Ataque")
|
| 356 |
+
|
| 357 |
+
with gr.Row():
|
| 358 |
+
eps_input = gr.Slider(
|
| 359 |
+
minimum=0.0,
|
| 360 |
+
maximum=1.0,
|
| 361 |
+
value=8/255,
|
| 362 |
+
step=1/255,
|
| 363 |
+
label="Epsilon (ε)"
|
| 364 |
+
)
|
| 365 |
+
alpha_input = gr.Slider(
|
| 366 |
+
minimum=0.0,
|
| 367 |
+
maximum=0.1,
|
| 368 |
+
value=2/255,
|
| 369 |
+
step=1/255,
|
| 370 |
+
label="Alpha (α)"
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
steps_input = gr.Slider(
|
| 374 |
+
minimum=1,
|
| 375 |
+
maximum=100,
|
| 376 |
+
value=10,
|
| 377 |
+
step=1,
|
| 378 |
+
label="Steps"
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
gr.Markdown("#### 👁️ Configuração da Atenção")
|
| 382 |
+
|
| 383 |
+
head_fusion_attack = gr.Radio(
|
| 384 |
+
choices=["mean", "max", "min"],
|
| 385 |
+
value="max",
|
| 386 |
+
label="Head Fusion"
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
with gr.Row():
|
| 390 |
+
discard_ratio_attack = gr.Slider(
|
| 391 |
+
minimum=0.0,
|
| 392 |
+
maximum=1.0,
|
| 393 |
+
value=0.9,
|
| 394 |
+
step=0.05,
|
| 395 |
+
label="Discard Ratio"
|
| 396 |
+
)
|
| 397 |
+
alpha_overlay_attack = gr.Slider(
|
| 398 |
+
minimum=0.0,
|
| 399 |
+
maximum=1.0,
|
| 400 |
+
value=0.7,
|
| 401 |
+
step=0.05,
|
| 402 |
+
label="Alpha Overlay"
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
attack_btn = gr.Button("🚀 Executar Análise Completa", variant="primary", size="lg")
|
| 406 |
+
|
| 407 |
+
with gr.Column(scale=2):
|
| 408 |
+
output_text_attack = gr.Markdown(label="Resultado")
|
| 409 |
+
|
| 410 |
+
with gr.Row():
|
| 411 |
+
with gr.Column():
|
| 412 |
+
gr.Markdown("**Imagem Adversarial Final**")
|
| 413 |
+
final_adv_image = gr.Image(type="pil", show_label=False)
|
| 414 |
+
with gr.Column():
|
| 415 |
+
gr.Markdown("**Todas as Iterações**")
|
| 416 |
+
iteration_gallery = gr.Gallery(
|
| 417 |
+
columns=5,
|
| 418 |
+
height="auto",
|
| 419 |
+
show_label=False
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
# Seção de Evolução da Atenção
|
| 423 |
+
gr.Markdown("---")
|
| 424 |
+
gr.Markdown("### 🔍 Evolução da Atenção Durante o Ataque")
|
| 425 |
+
gr.Markdown("_Compare a imagem da iteração (esquerda) com o mapa de atenção (direita)_")
|
| 426 |
+
|
| 427 |
+
# ImageSlider para comparação lado a lado!
|
| 428 |
+
iteration_comparison = gr.ImageSlider(
|
| 429 |
+
label="Iteração vs Atenção",
|
| 430 |
+
type="pil",
|
| 431 |
+
interactive=False
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
iteration_slider = gr.Slider(
|
| 435 |
+
minimum=0,
|
| 436 |
+
maximum=10,
|
| 437 |
+
step=1,
|
| 438 |
+
value=0,
|
| 439 |
+
label="Iteração do Ataque"
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
# States para armazenar as imagens
|
| 443 |
+
attention_overlays_state = gr.State([])
|
| 444 |
+
iteration_images_state = gr.State([])
|
| 445 |
+
|
| 446 |
+
# Função para atualizar ImageSlider baseado no slider
|
| 447 |
+
def update_iteration_view(iteration_idx, iteration_images, attention_overlays):
|
| 448 |
+
if not iteration_images or not attention_overlays:
|
| 449 |
+
return None
|
| 450 |
+
|
| 451 |
+
idx = int(iteration_idx)
|
| 452 |
+
if idx >= len(iteration_images):
|
| 453 |
+
idx = len(iteration_images) - 1
|
| 454 |
+
|
| 455 |
+
# ImageSlider espera uma tupla (img_esquerda, img_direita)
|
| 456 |
+
return (iteration_images[idx], attention_overlays[idx])
|
| 457 |
+
|
| 458 |
+
# Events
|
| 459 |
+
attack_btn.click(
|
| 460 |
+
fn=run_pgd_attack,
|
| 461 |
+
inputs=[
|
| 462 |
+
model_upload_attack, image_upload_attack, labels_upload_attack,
|
| 463 |
+
eps_input, alpha_input, steps_input,
|
| 464 |
+
discard_ratio_attack, head_fusion_attack, alpha_overlay_attack
|
| 465 |
+
],
|
| 466 |
+
outputs=[iteration_images_state, output_text_attack, final_adv_image, attention_overlays_state]
|
| 467 |
+
).then(
|
| 468 |
+
fn=lambda x: x,
|
| 469 |
+
inputs=[iteration_images_state],
|
| 470 |
+
outputs=[iteration_gallery]
|
| 471 |
+
).then(
|
| 472 |
+
fn=lambda imgs: gr.update(maximum=len(imgs)-1 if imgs else 0, value=0),
|
| 473 |
+
inputs=[iteration_images_state],
|
| 474 |
+
outputs=[iteration_slider]
|
| 475 |
+
).then(
|
| 476 |
+
fn=update_iteration_view,
|
| 477 |
+
inputs=[iteration_slider, iteration_images_state, attention_overlays_state],
|
| 478 |
+
outputs=[iteration_comparison]
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
# Update quando mexer no slider
|
| 482 |
+
iteration_slider.change(
|
| 483 |
+
fn=update_iteration_view,
|
| 484 |
+
inputs=[iteration_slider, iteration_images_state, attention_overlays_state],
|
| 485 |
+
outputs=[iteration_comparison],
|
| 486 |
+
show_progress="hidden" # Remove loading - imagem simplesmente troca!
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
# Tab 3: Visualização de Atenção
|
| 490 |
+
with gr.Tab("👁️ Attention Visualization"):
|
| 491 |
+
gr.Markdown("### Visualize onde o modelo está 'olhando' na imagem")
|
| 492 |
+
|
| 493 |
+
with gr.Row():
|
| 494 |
+
with gr.Column():
|
| 495 |
+
model_upload_attention = gr.File(
|
| 496 |
+
label="Upload Model (.pth/.pt)",
|
| 497 |
+
file_types=[".pth", ".pt"]
|
| 498 |
+
)
|
| 499 |
+
labels_upload_attention = gr.File(
|
| 500 |
+
label="Upload Class Labels (opcional - .txt/.json)",
|
| 501 |
+
file_types=[".txt", ".json"]
|
| 502 |
+
)
|
| 503 |
+
image_upload_attention = gr.Image(
|
| 504 |
+
label="Upload Image",
|
| 505 |
+
type="pil"
|
| 506 |
+
)
|
| 507 |
+
|
| 508 |
+
gr.Markdown("#### Configuração da Visualização")
|
| 509 |
+
|
| 510 |
+
head_fusion_input = gr.Radio(
|
| 511 |
+
choices=["mean", "max", "min"],
|
| 512 |
+
value="max",
|
| 513 |
+
label="Head Fusion - Como agregar múltiplas cabeças de atenção"
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
discard_ratio_input = gr.Slider(
|
| 517 |
+
minimum=0.0,
|
| 518 |
+
maximum=1.0,
|
| 519 |
+
value=0.9,
|
| 520 |
+
step=0.05,
|
| 521 |
+
label="Discard Ratio - Proporção de atenções fracas a descartar"
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
alpha_overlay_input = gr.Slider(
|
| 525 |
+
minimum=0.0,
|
| 526 |
+
maximum=1.0,
|
| 527 |
+
value=0.7,
|
| 528 |
+
step=0.05,
|
| 529 |
+
label="Peso da Imagem Original (alpha) - 0.7 = 70% imagem, 30% heatmap"
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
attention_btn = gr.Button("👁️ Visualizar Atenção", variant="primary")
|
| 533 |
+
|
| 534 |
+
with gr.Column():
|
| 535 |
+
output_text_attention = gr.Markdown(label="Resultado")
|
| 536 |
+
attention_output = gr.Image(label="Mapa de Atenção Sobreposto", type="pil")
|
| 537 |
+
|
| 538 |
+
# Event: visualizar atenção
|
| 539 |
+
attention_btn.click(
|
| 540 |
+
fn=visualize_attention,
|
| 541 |
+
inputs=[
|
| 542 |
+
model_upload_attention,
|
| 543 |
+
image_upload_attention,
|
| 544 |
+
labels_upload_attention,
|
| 545 |
+
discard_ratio_input,
|
| 546 |
+
head_fusion_input,
|
| 547 |
+
alpha_overlay_input
|
| 548 |
+
],
|
| 549 |
+
outputs=[attention_output, output_text_attention]
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
+
return app
|
| 553 |
+
|
| 554 |
+
if __name__ == "__main__":
|
| 555 |
+
app = create_app()
|
| 556 |
+
app.launch(
|
| 557 |
+
server_name="0.0.0.0",
|
| 558 |
+
server_port=7861,
|
| 559 |
+
share=False
|
| 560 |
+
)
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
torch>=2.0.0
|
| 3 |
+
torchvision>=0.15.0
|
| 4 |
+
timm>=0.9.0
|
| 5 |
+
torchattacks>=3.5.0
|
| 6 |
+
numpy>=1.24.0
|
| 7 |
+
opencv-python>=4.8.0
|
| 8 |
+
matplotlib>=3.7.0
|
| 9 |
+
Pillow>=10.0.0
|
utils/attacks.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torchattacks
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from typing import List, Tuple
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def denormalize_imagenet(tensor: torch.Tensor) -> torch.Tensor:
|
| 9 |
+
"""
|
| 10 |
+
Reverte a normalização ImageNet de um tensor.
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
tensor: Tensor normalizado (CxHxW) com mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
|
| 14 |
+
|
| 15 |
+
Returns:
|
| 16 |
+
Tensor desnormalizado com valores em [0, 1]
|
| 17 |
+
"""
|
| 18 |
+
mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1).to(tensor.device)
|
| 19 |
+
std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1).to(tensor.device)
|
| 20 |
+
|
| 21 |
+
# Inverte: x_norm = (x - mean) / std => x = x_norm * std + mean
|
| 22 |
+
denorm = tensor * std + mean
|
| 23 |
+
|
| 24 |
+
# Clip para garantir [0, 1]
|
| 25 |
+
return torch.clamp(denorm, 0, 1)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def tensor_to_pil(tensor: torch.Tensor, denormalize: bool = True) -> Image.Image:
|
| 29 |
+
"""
|
| 30 |
+
Converte tensor (CxHxW) para PIL Image RGB.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
tensor: Tensor com shape (C, H, W)
|
| 34 |
+
denormalize: Se True, aplica desnormalização ImageNet antes da conversão
|
| 35 |
+
|
| 36 |
+
Returns:
|
| 37 |
+
PIL Image no espaço RGB [0, 255]
|
| 38 |
+
"""
|
| 39 |
+
if denormalize:
|
| 40 |
+
tensor = denormalize_imagenet(tensor)
|
| 41 |
+
|
| 42 |
+
# tensor shape: (C, H, W) com valores [0, 1]
|
| 43 |
+
img_np = tensor.cpu().detach().numpy()
|
| 44 |
+
img_np = np.transpose(img_np, (1, 2, 0)) # HxWxC
|
| 45 |
+
img_np = (img_np * 255).clip(0, 255).astype(np.uint8)
|
| 46 |
+
return Image.fromarray(img_np, mode='RGB')
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class PGDIterations(torchattacks.PGD):
|
| 50 |
+
"""
|
| 51 |
+
Extensão do ataque PGD padrão que captura e retorna
|
| 52 |
+
as imagens adversariais de cada iteração como lista de PIL Images.
|
| 53 |
+
"""
|
| 54 |
+
def __init__(self, model, eps=0.05, alpha=0.005, steps=10, random_start=True):
|
| 55 |
+
# Inicializa PGD padrão com os parâmetros
|
| 56 |
+
super().__init__(model, eps=eps, alpha=alpha, steps=steps, random_start=random_start)
|
| 57 |
+
self.iteration_images: List[Image.Image] = []
|
| 58 |
+
self.iteration_tensors: List[torch.Tensor] = []
|
| 59 |
+
|
| 60 |
+
def forward(self, images, labels) -> Tuple[torch.Tensor, List[Image.Image]]:
|
| 61 |
+
"""
|
| 62 |
+
Executa o ataque PGD e retorna:
|
| 63 |
+
- adv_images: tensor adversarial final
|
| 64 |
+
- iteration_images: lista de PIL Images (uma por iteração do ataque)
|
| 65 |
+
|
| 66 |
+
Implementação adaptada para trabalhar com imagens normalizadas ImageNet.
|
| 67 |
+
"""
|
| 68 |
+
images = images.clone().detach().to(self.device)
|
| 69 |
+
labels = labels.clone().detach().to(self.device)
|
| 70 |
+
|
| 71 |
+
# Para targeted attack (se implementarmos no futuro)
|
| 72 |
+
if self.targeted:
|
| 73 |
+
target_labels = self.get_target_label(images, labels)
|
| 74 |
+
|
| 75 |
+
loss = torch.nn.CrossEntropyLoss()
|
| 76 |
+
adv_images = images.clone().detach()
|
| 77 |
+
|
| 78 |
+
# Desnormalizar para aplicar eps e clipping no espaço correto [0,1]
|
| 79 |
+
mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(self.device)
|
| 80 |
+
std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(self.device)
|
| 81 |
+
|
| 82 |
+
# Converter para espaço [0,1]
|
| 83 |
+
images_denorm = images * std + mean
|
| 84 |
+
adv_images_denorm = images_denorm.clone().detach()
|
| 85 |
+
|
| 86 |
+
if self.random_start:
|
| 87 |
+
# Starting at a uniformly random point no espaço [0,1]
|
| 88 |
+
adv_images_denorm = adv_images_denorm + torch.empty_like(adv_images_denorm).uniform_(-self.eps, self.eps)
|
| 89 |
+
adv_images_denorm = torch.clamp(adv_images_denorm, min=0, max=1).detach()
|
| 90 |
+
|
| 91 |
+
self.iteration_images = []
|
| 92 |
+
self.iteration_tensors = []
|
| 93 |
+
|
| 94 |
+
# Salvar iteração 0 (imagem original)
|
| 95 |
+
pil_img_orig = tensor_to_pil(images_denorm[0], denormalize=False)
|
| 96 |
+
self.iteration_images.append(pil_img_orig)
|
| 97 |
+
self.iteration_tensors.append(images.clone().detach())
|
| 98 |
+
|
| 99 |
+
for _ in range(self.steps):
|
| 100 |
+
# Normalizar para passar pelo modelo
|
| 101 |
+
adv_images = (adv_images_denorm - mean) / std
|
| 102 |
+
adv_images.requires_grad = True
|
| 103 |
+
outputs = self.get_logits(adv_images)
|
| 104 |
+
|
| 105 |
+
# Calculate loss
|
| 106 |
+
if self.targeted:
|
| 107 |
+
cost = -loss(outputs, target_labels)
|
| 108 |
+
else:
|
| 109 |
+
cost = loss(outputs, labels)
|
| 110 |
+
|
| 111 |
+
# Update adversarial images
|
| 112 |
+
grad = torch.autograd.grad(cost, adv_images,
|
| 113 |
+
retain_graph=False, create_graph=False)[0]
|
| 114 |
+
|
| 115 |
+
# Voltar para espaço desnormalizado para aplicar perturbação
|
| 116 |
+
adv_images_denorm = adv_images_denorm.detach() + self.alpha * grad.sign() * std
|
| 117 |
+
delta = torch.clamp(adv_images_denorm - images_denorm, min=-self.eps, max=self.eps)
|
| 118 |
+
adv_images_denorm = torch.clamp(images_denorm + delta, min=0, max=1).detach()
|
| 119 |
+
|
| 120 |
+
# Normalizar para salvar tensor
|
| 121 |
+
adv_images_normalized = (adv_images_denorm - mean) / std
|
| 122 |
+
|
| 123 |
+
# Capturar imagem e tensor desta iteração
|
| 124 |
+
pil_img = tensor_to_pil(adv_images_denorm[0], denormalize=False)
|
| 125 |
+
self.iteration_images.append(pil_img)
|
| 126 |
+
self.iteration_tensors.append(adv_images_normalized.clone().detach())
|
| 127 |
+
|
| 128 |
+
# Retornar imagem normalizada para o modelo
|
| 129 |
+
adv_images = (adv_images_denorm - mean) / std
|
| 130 |
+
return adv_images, self.iteration_images
|
utils/inference.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Tuple, Optional
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def predict_topk(
|
| 6 |
+
model: torch.nn.Module,
|
| 7 |
+
img_tensor: torch.Tensor,
|
| 8 |
+
top_k: int = 5,
|
| 9 |
+
device: Optional[torch.device] = None,
|
| 10 |
+
) -> Tuple[torch.Tensor, torch.Tensor, int, torch.Tensor]:
|
| 11 |
+
"""Retorna top_k probabilidades e índices, número total de classes e vetor de probabilidades completo.
|
| 12 |
+
|
| 13 |
+
Saída: (top_prob, top_idx, num_classes, probabilities)
|
| 14 |
+
"""
|
| 15 |
+
if device is not None:
|
| 16 |
+
img_tensor = img_tensor.to(device)
|
| 17 |
+
model.eval()
|
| 18 |
+
with torch.no_grad():
|
| 19 |
+
output = model(img_tensor)
|
| 20 |
+
if isinstance(output, tuple):
|
| 21 |
+
output = output[0]
|
| 22 |
+
logits = output[0]
|
| 23 |
+
probabilities = torch.nn.functional.softmax(logits, dim=0)
|
| 24 |
+
num_classes = probabilities.shape[0]
|
| 25 |
+
k = min(top_k, num_classes)
|
| 26 |
+
top_prob, top_idx = torch.topk(probabilities, k)
|
| 27 |
+
return top_prob, top_idx, num_classes, probabilities
|
utils/model_loader.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pickle
|
| 2 |
+
import torch
|
| 3 |
+
import timm
|
| 4 |
+
from typing import Optional, Tuple, Dict, Any
|
| 5 |
+
|
| 6 |
+
DEVICE_DEFAULT = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class CustomUnpickler(pickle.Unpickler):
|
| 10 |
+
"""Unpickler que ignora classes customizadas ausentes criando dummies dinamicamente."""
|
| 11 |
+
|
| 12 |
+
def find_class(self, module, name):
|
| 13 |
+
try:
|
| 14 |
+
return super().find_class(module, name)
|
| 15 |
+
except Exception:
|
| 16 |
+
# Cria uma classe dummy com o mesmo nome para permitir o unpickle
|
| 17 |
+
return type(name, (), {})
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def load_checkpoint(model_path: str, device: Optional[torch.device] = None) -> Any:
|
| 21 |
+
"""Carrega um checkpoint/modelo do caminho informado, com fallback para unpickler customizado.
|
| 22 |
+
|
| 23 |
+
Retorna o objeto carregado (modelo completo, state_dict ou dict de checkpoint).
|
| 24 |
+
"""
|
| 25 |
+
device = device or DEVICE_DEFAULT
|
| 26 |
+
try:
|
| 27 |
+
return torch.load(model_path, map_location=device, weights_only=False)
|
| 28 |
+
except (AttributeError, ModuleNotFoundError, RuntimeError):
|
| 29 |
+
# Fallback quando há classes ausentes ou conflitos de versão
|
| 30 |
+
with open(model_path, 'rb') as f:
|
| 31 |
+
return CustomUnpickler(f).load()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def infer_num_classes(state_dict: Dict[str, torch.Tensor]) -> int:
|
| 35 |
+
"""Infere o número de classes a partir do state_dict (camada de head).
|
| 36 |
+
|
| 37 |
+
Caso não encontre, retorna 1000 (padrão ImageNet).
|
| 38 |
+
"""
|
| 39 |
+
for key, tensor in state_dict.items():
|
| 40 |
+
if 'head' in key and 'weight' in key and hasattr(tensor, 'shape'):
|
| 41 |
+
return tensor.shape[0]
|
| 42 |
+
return 1000
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def extract_class_names(checkpoint: Any) -> Optional[Dict[int, str]]:
|
| 46 |
+
"""Tenta extrair nomes de classes de um checkpoint (se presente)."""
|
| 47 |
+
if not isinstance(checkpoint, dict):
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
possible_keys = [
|
| 51 |
+
'class_names', 'classes', 'class_to_idx', 'idx_to_class',
|
| 52 |
+
'label_names', 'labels', 'class_labels'
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
for key in possible_keys:
|
| 56 |
+
if key in checkpoint:
|
| 57 |
+
labels = checkpoint[key]
|
| 58 |
+
if isinstance(labels, list):
|
| 59 |
+
return {i: name for i, name in enumerate(labels)}
|
| 60 |
+
if isinstance(labels, dict):
|
| 61 |
+
# Se já for idx->nome
|
| 62 |
+
if all(isinstance(k, int) for k in labels.keys()):
|
| 63 |
+
return labels # type: ignore[return-value]
|
| 64 |
+
# Se for nome->idx
|
| 65 |
+
if all(isinstance(v, int) for v in labels.values()):
|
| 66 |
+
return {v: k for k, v in labels.items()}
|
| 67 |
+
return labels # type: ignore[return-value]
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def load_class_names_from_file(labels_file: Optional[str]) -> Optional[Dict[int, str]]:
|
| 72 |
+
"""Carrega nomes de classes de um arquivo .txt (um por linha) ou .json (lista ou dict)."""
|
| 73 |
+
if not labels_file:
|
| 74 |
+
return None
|
| 75 |
+
import json
|
| 76 |
+
try:
|
| 77 |
+
if labels_file.endswith('.json'):
|
| 78 |
+
with open(labels_file, 'r', encoding='utf-8') as f:
|
| 79 |
+
data = json.load(f)
|
| 80 |
+
if isinstance(data, list):
|
| 81 |
+
return {i: name for i, name in enumerate(data)}
|
| 82 |
+
if isinstance(data, dict):
|
| 83 |
+
out: Dict[int, str] = {}
|
| 84 |
+
for k, v in data.items():
|
| 85 |
+
try:
|
| 86 |
+
out[int(k)] = v
|
| 87 |
+
except Exception:
|
| 88 |
+
# Ignora chaves não numéricas
|
| 89 |
+
pass
|
| 90 |
+
if out:
|
| 91 |
+
return out
|
| 92 |
+
# fallback se for nome->idx
|
| 93 |
+
if all(isinstance(v, int) for v in data.values()):
|
| 94 |
+
return {v: k for k, v in data.items()}
|
| 95 |
+
return None
|
| 96 |
+
else:
|
| 97 |
+
with open(labels_file, 'r', encoding='utf-8') as f:
|
| 98 |
+
lines = [line.strip() for line in f if line.strip()]
|
| 99 |
+
return {i: name for i, name in enumerate(lines)}
|
| 100 |
+
except Exception:
|
| 101 |
+
return None
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def build_model_from_checkpoint(checkpoint: Any, device: Optional[torch.device] = None) -> torch.nn.Module:
|
| 105 |
+
"""Constroi um modelo a partir de um checkpoint que pode ser um dict, state_dict ou o próprio modelo."""
|
| 106 |
+
device = device or DEVICE_DEFAULT
|
| 107 |
+
if isinstance(checkpoint, dict):
|
| 108 |
+
if 'model' in checkpoint:
|
| 109 |
+
model = checkpoint['model']
|
| 110 |
+
elif 'state_dict' in checkpoint:
|
| 111 |
+
state_dict = checkpoint['state_dict']
|
| 112 |
+
num_classes = infer_num_classes(state_dict)
|
| 113 |
+
model = timm.create_model('vit_base_patch16_224', pretrained=False, num_classes=num_classes)
|
| 114 |
+
model.load_state_dict(state_dict)
|
| 115 |
+
else:
|
| 116 |
+
# assume dict é um state_dict
|
| 117 |
+
num_classes = infer_num_classes(checkpoint)
|
| 118 |
+
model = timm.create_model('vit_base_patch16_224', pretrained=False, num_classes=num_classes)
|
| 119 |
+
model.load_state_dict(checkpoint)
|
| 120 |
+
else:
|
| 121 |
+
# modelo completo salvo via torch.save(model, ...)
|
| 122 |
+
model = checkpoint
|
| 123 |
+
|
| 124 |
+
model = model.to(device)
|
| 125 |
+
model.eval()
|
| 126 |
+
return model
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def load_model_and_labels(
|
| 130 |
+
model_path: str,
|
| 131 |
+
labels_file: Optional[str] = None,
|
| 132 |
+
device: Optional[torch.device] = None,
|
| 133 |
+
) -> Tuple[torch.nn.Module, Optional[Dict[int, str]], Optional[str]]:
|
| 134 |
+
"""
|
| 135 |
+
** Função Principal **
|
| 136 |
+
Carrega modelo e, se disponível, nomes de classes.
|
| 137 |
+
|
| 138 |
+
Retorna: (model, class_names, origem_labels) onde origem_labels ∈ {"file", "checkpoint", None}
|
| 139 |
+
None se não houver nomes de classes disponíveis.
|
| 140 |
+
"""
|
| 141 |
+
device = device or DEVICE_DEFAULT
|
| 142 |
+
checkpoint = load_checkpoint(model_path, device=device)
|
| 143 |
+
class_names_ckpt = extract_class_names(checkpoint)
|
| 144 |
+
class_names_file = load_class_names_from_file(labels_file)
|
| 145 |
+
class_names = class_names_file or class_names_ckpt
|
| 146 |
+
source: Optional[str] = None
|
| 147 |
+
if class_names_file:
|
| 148 |
+
source = 'file'
|
| 149 |
+
elif class_names_ckpt:
|
| 150 |
+
source = 'checkpoint'
|
| 151 |
+
|
| 152 |
+
model = build_model_from_checkpoint(checkpoint, device=device)
|
| 153 |
+
return model, class_names, source
|
utils/preprocessing.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Union
|
| 2 |
+
from PIL import Image
|
| 3 |
+
from torchvision import transforms
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def get_default_transform() -> transforms.Compose:
|
| 8 |
+
"""Transform padrão (Resize+CenterCrop+Normalize) compatível com modelos ImageNet."""
|
| 9 |
+
return transforms.Compose([
|
| 10 |
+
transforms.Resize(256),
|
| 11 |
+
transforms.CenterCrop(224),
|
| 12 |
+
transforms.ToTensor(),
|
| 13 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 14 |
+
])
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def preprocess_image(
|
| 18 |
+
image: Union[str, Image.Image],
|
| 19 |
+
transform: Optional[transforms.Compose] = None,
|
| 20 |
+
) -> torch.Tensor:
|
| 21 |
+
"""Carrega e transforma uma imagem (caminho ou PIL) retornando um tensor 1xCxHxW."""
|
| 22 |
+
transform = transform or get_default_transform()
|
| 23 |
+
|
| 24 |
+
if isinstance(image, str):
|
| 25 |
+
img = Image.open(image).convert('RGB')
|
| 26 |
+
elif isinstance(image, Image.Image):
|
| 27 |
+
img = image.convert('RGB')
|
| 28 |
+
else:
|
| 29 |
+
raise ValueError("Imagem inválida: informe caminho ou PIL.Image")
|
| 30 |
+
|
| 31 |
+
return transform(img).unsqueeze(0)
|
utils/visualization.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import matplotlib.cm as cm
|
| 6 |
+
from torchvision.models.feature_extraction import create_feature_extractor
|
| 7 |
+
from typing import Dict, Tuple
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def extract_attention_maps(model, image: torch.Tensor) -> list:
|
| 11 |
+
"""
|
| 12 |
+
Extrai attention maps de todas as camadas do ViT usando hooks.
|
| 13 |
+
|
| 14 |
+
Implementação simplificada e robusta que calcula attention manualmente.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
model: Modelo ViT
|
| 18 |
+
image: Tensor de imagem [1, 3, 224, 224]
|
| 19 |
+
|
| 20 |
+
Returns:
|
| 21 |
+
attentions: lista de tensores [batch, heads, patches, patches]
|
| 22 |
+
"""
|
| 23 |
+
attentions = []
|
| 24 |
+
|
| 25 |
+
# Função de hook simplificada que captura entrada e calcula attention
|
| 26 |
+
def make_attention_hook():
|
| 27 |
+
def hook(module, input, output):
|
| 28 |
+
x = input[0] # Input do módulo de atenção
|
| 29 |
+
B, N, C = x.shape
|
| 30 |
+
|
| 31 |
+
# Verificar se tem os componentes necessários
|
| 32 |
+
if not (hasattr(module, 'qkv') and hasattr(module, 'num_heads')):
|
| 33 |
+
return
|
| 34 |
+
|
| 35 |
+
# Calcular Q, K, V
|
| 36 |
+
qkv = module.qkv(x).reshape(B, N, 3, module.num_heads, C // module.num_heads).permute(2, 0, 3, 1, 4)
|
| 37 |
+
q, k, v = qkv.unbind(0)
|
| 38 |
+
|
| 39 |
+
# Calcular attention weights
|
| 40 |
+
scale = (C // module.num_heads) ** -0.5
|
| 41 |
+
attn = (q @ k.transpose(-2, -1)) * scale
|
| 42 |
+
attn = attn.softmax(dim=-1)
|
| 43 |
+
|
| 44 |
+
# Salvar (já no CPU para não acumular na GPU)
|
| 45 |
+
attentions.append(attn.detach().cpu())
|
| 46 |
+
|
| 47 |
+
return hook
|
| 48 |
+
|
| 49 |
+
# Encontrar e registrar hooks nos módulos de atenção
|
| 50 |
+
hooks = []
|
| 51 |
+
if not hasattr(model, 'blocks'):
|
| 52 |
+
raise ValueError("Modelo não tem atributo 'blocks'. Não é um ViT compatível.")
|
| 53 |
+
|
| 54 |
+
for i, block in enumerate(model.blocks):
|
| 55 |
+
if hasattr(block, 'attn'):
|
| 56 |
+
hook = block.attn.register_forward_hook(make_attention_hook())
|
| 57 |
+
hooks.append(hook)
|
| 58 |
+
|
| 59 |
+
if len(hooks) == 0:
|
| 60 |
+
raise ValueError("Não foi possível registrar hooks. Verifique a arquitetura do modelo.")
|
| 61 |
+
|
| 62 |
+
# Executar forward pass
|
| 63 |
+
model.eval()
|
| 64 |
+
with torch.inference_mode():
|
| 65 |
+
_ = model(image)
|
| 66 |
+
|
| 67 |
+
# Remover hooks
|
| 68 |
+
for hook in hooks:
|
| 69 |
+
hook.remove()
|
| 70 |
+
|
| 71 |
+
if len(attentions) == 0:
|
| 72 |
+
raise ValueError(
|
| 73 |
+
f"Nenhuma atenção capturada após registrar {len(hooks)} hooks. "
|
| 74 |
+
f"A arquitetura do modelo pode não ser compatível."
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
return attentions
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def attention_rollout(attentions: list,
|
| 81 |
+
discard_ratio: float = 0.9,
|
| 82 |
+
head_fusion: str = 'max') -> np.ndarray:
|
| 83 |
+
"""
|
| 84 |
+
Implementa Attention Rollout seguindo a implementação original.
|
| 85 |
+
|
| 86 |
+
Referência: https://github.com/jacobgil/vit-explain
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
attentions: Lista de tensores [batch, heads, patches, patches]
|
| 90 |
+
discard_ratio: Proporção de atenções mais fracas a descartar (default: 0.9)
|
| 91 |
+
head_fusion: Como agregar múltiplas cabeças - 'mean', 'max' ou 'min'
|
| 92 |
+
|
| 93 |
+
Returns:
|
| 94 |
+
mask: Array numpy [grid_size, grid_size] com valores normalizados [0, 1]
|
| 95 |
+
"""
|
| 96 |
+
# Inicializar com matriz identidade (CORREÇÃO 1)
|
| 97 |
+
result = torch.eye(attentions[0].size(-1))
|
| 98 |
+
|
| 99 |
+
with torch.no_grad():
|
| 100 |
+
for attention in attentions:
|
| 101 |
+
# Agregar heads (CORREÇÃO 2: usar axis=1, não dim=0)
|
| 102 |
+
if head_fusion == 'mean':
|
| 103 |
+
attention_heads_fused = attention.mean(axis=1)
|
| 104 |
+
elif head_fusion == 'max':
|
| 105 |
+
attention_heads_fused = attention.max(axis=1)[0]
|
| 106 |
+
elif head_fusion == 'min':
|
| 107 |
+
attention_heads_fused = attention.min(axis=1)[0]
|
| 108 |
+
else:
|
| 109 |
+
raise ValueError(f"head_fusion deve ser 'mean', 'max' ou 'min'")
|
| 110 |
+
|
| 111 |
+
# Descartar atenções fracas, mas proteger CLS token
|
| 112 |
+
flat = attention_heads_fused.view(attention_heads_fused.size(0), -1)
|
| 113 |
+
_, indices = flat.topk(int(flat.size(-1) * discard_ratio), -1, False)
|
| 114 |
+
indices = indices[indices != 0] # Proteger CLS token
|
| 115 |
+
flat[0, indices] = 0
|
| 116 |
+
|
| 117 |
+
# Adicionar identidade e normalizar
|
| 118 |
+
I = torch.eye(attention_heads_fused.size(-1))
|
| 119 |
+
a = (attention_heads_fused + 1.0 * I) / 2
|
| 120 |
+
|
| 121 |
+
# CORREÇÃO 3: normalizar sem keepdim
|
| 122 |
+
a = a / a.sum(dim=-1)
|
| 123 |
+
|
| 124 |
+
# Rollout recursivo
|
| 125 |
+
result = torch.matmul(a, result)
|
| 126 |
+
|
| 127 |
+
# CORREÇÃO 4: Extrair atenção do CLS token (batch, CLS, patches)
|
| 128 |
+
# Look at the total attention between the class token and the image patches
|
| 129 |
+
mask = result[0, 0, 1:]
|
| 130 |
+
|
| 131 |
+
# Calcular tamanho do grid
|
| 132 |
+
width = int(mask.size(-1) ** 0.5)
|
| 133 |
+
mask = mask.reshape(width, width).numpy()
|
| 134 |
+
|
| 135 |
+
# Normalizar
|
| 136 |
+
mask = mask / np.max(mask)
|
| 137 |
+
|
| 138 |
+
return mask
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def create_attention_overlay(original_image: Image.Image,
|
| 142 |
+
attention_mask: np.ndarray,
|
| 143 |
+
alpha: float = 0.5,
|
| 144 |
+
colormap: str = 'jet') -> Image.Image:
|
| 145 |
+
"""
|
| 146 |
+
Cria visualização sobrepondo o mapa de atenção na imagem original.
|
| 147 |
+
|
| 148 |
+
Segue implementação de referência usando OpenCV.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
original_image: Imagem PIL original
|
| 152 |
+
attention_mask: Máscara de atenção [H, W] normalizada [0, 1]
|
| 153 |
+
alpha: Peso da imagem original (0.7 = 70% imagem, 30% heatmap)
|
| 154 |
+
colormap: 'jet' (padrão OpenCV)
|
| 155 |
+
|
| 156 |
+
Returns:
|
| 157 |
+
Imagem PIL com overlay de atenção
|
| 158 |
+
"""
|
| 159 |
+
import cv2
|
| 160 |
+
|
| 161 |
+
# Converter PIL para numpy array RGB
|
| 162 |
+
img_np = np.array(original_image).astype(np.float32) / 255.0
|
| 163 |
+
|
| 164 |
+
# Redimensionar máscara para o tamanho da imagem (224x224 ou tamanho original)
|
| 165 |
+
h, w = img_np.shape[:2]
|
| 166 |
+
mask_resized = cv2.resize(attention_mask, (w, h))
|
| 167 |
+
|
| 168 |
+
# Aplicar colormap do OpenCV (retorna BGR!)
|
| 169 |
+
heatmap = cv2.applyColorMap(np.uint8(255 * mask_resized), cv2.COLORMAP_JET)
|
| 170 |
+
|
| 171 |
+
# CRÍTICO: Converter BGR → RGB (OpenCV usa BGR!)
|
| 172 |
+
heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB)
|
| 173 |
+
heatmap = heatmap.astype(np.float32) / 255.0
|
| 174 |
+
|
| 175 |
+
# Blend: alpha * img_original + (1-alpha) * heatmap
|
| 176 |
+
overlay = alpha * img_np + (1 - alpha) * heatmap
|
| 177 |
+
overlay = np.clip(overlay, 0, 1)
|
| 178 |
+
|
| 179 |
+
# Converter de volta para PIL
|
| 180 |
+
overlay_uint8 = (overlay * 255).astype(np.uint8)
|
| 181 |
+
return Image.fromarray(overlay_uint8)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def extract_attention_for_iterations(
|
| 185 |
+
model,
|
| 186 |
+
iteration_tensors: list,
|
| 187 |
+
discard_ratio: float = 0.9,
|
| 188 |
+
head_fusion: str = 'max'
|
| 189 |
+
) -> list:
|
| 190 |
+
"""
|
| 191 |
+
Extrai mapas de atenção para cada iteração do ataque PGD.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
model: Modelo ViT
|
| 195 |
+
iteration_tensors: Lista de tensors normalizados [1, 3, 224, 224] de cada iteração
|
| 196 |
+
discard_ratio: Proporção de atenções fracas a descartar
|
| 197 |
+
head_fusion: Como agregar heads ('mean', 'max', 'min')
|
| 198 |
+
|
| 199 |
+
Returns:
|
| 200 |
+
Lista de máscaras de atenção [14, 14] normalizadas [0, 1]
|
| 201 |
+
"""
|
| 202 |
+
attention_masks = []
|
| 203 |
+
|
| 204 |
+
for tensor in iteration_tensors:
|
| 205 |
+
# Extrair attention maps para esta iteração
|
| 206 |
+
attentions = extract_attention_maps(model, tensor)
|
| 207 |
+
|
| 208 |
+
# Aplicar Attention Rollout
|
| 209 |
+
mask = attention_rollout(
|
| 210 |
+
attentions,
|
| 211 |
+
discard_ratio=discard_ratio,
|
| 212 |
+
head_fusion=head_fusion
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
attention_masks.append(mask)
|
| 216 |
+
|
| 217 |
+
return attention_masks
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def create_iteration_attention_overlays(
|
| 221 |
+
iteration_images: list,
|
| 222 |
+
attention_masks: list,
|
| 223 |
+
alpha: float = 0.7
|
| 224 |
+
) -> list:
|
| 225 |
+
"""
|
| 226 |
+
Cria overlays de atenção para cada iteração do ataque.
|
| 227 |
+
OTIMIZADO para velocidade de renderização.
|
| 228 |
+
|
| 229 |
+
Args:
|
| 230 |
+
iteration_images: Lista de PIL Images (uma por iteração)
|
| 231 |
+
attention_masks: Lista de máscaras de atenção [14, 14]
|
| 232 |
+
alpha: Transparência do overlay
|
| 233 |
+
|
| 234 |
+
Returns:
|
| 235 |
+
Lista de PIL Images com heatmaps sobrepostos (comprimidas)
|
| 236 |
+
"""
|
| 237 |
+
overlays = []
|
| 238 |
+
|
| 239 |
+
for img, mask in zip(iteration_images, attention_masks):
|
| 240 |
+
overlay = create_attention_overlay(img, mask, alpha=alpha)
|
| 241 |
+
|
| 242 |
+
# OTIMIZAÇÃO AGRESSIVA: reduzir para 224x224 JPEG qualidade 75
|
| 243 |
+
overlay = overlay.resize((224, 224), Image.LANCZOS)
|
| 244 |
+
|
| 245 |
+
# Converter para RGB se necessário (JPEG não suporta RGBA)
|
| 246 |
+
if overlay.mode in ('RGBA', 'LA', 'P'):
|
| 247 |
+
background = Image.new('RGB', overlay.size, (255, 255, 255))
|
| 248 |
+
if overlay.mode == 'P':
|
| 249 |
+
overlay = overlay.convert('RGBA')
|
| 250 |
+
background.paste(overlay, mask=overlay.split()[-1] if overlay.mode == 'RGBA' else None)
|
| 251 |
+
overlay = background
|
| 252 |
+
|
| 253 |
+
overlays.append(overlay)
|
| 254 |
+
|
| 255 |
+
return overlays
|
| 256 |
+
|