File size: 3,672 Bytes
9ae1b1e |
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 |
import torch
from torch.nn.functional import normalize
def check_anomaly_theoretical(
x,
H,
W,
anomaly_dir=None,
temperature=0.1,
mask_thr=0.001,
kernel=3,
):
x_token = x[:, 1:]
B = x.shape[0]
assert B == 1
x_token = x_token.reshape(H, W, -1).contiguous()
with torch.no_grad():
feature = normalize(x_token, dim=-1)
direction = normalize(anomaly_dir, dim=-1)
logits = -(feature * direction).sum(dim=-1).abs()
prob = torch.exp(logits / temperature)
assert kernel in (3, 5)
pad = kernel // 2
w = prob.unfold(0, kernel, 1).unfold(1, kernel, 1)
w = w / w.sum(dim=(-1, -2), keepdims=True)
if kernel == 3:
gaussian = (
torch.FloatTensor(
[
1 / 16,
1 / 8,
1 / 16,
1 / 8,
1 / 4,
1 / 8,
1 / 16,
1 / 8,
1 / 16,
]
)
.to(w.device)
.reshape(1, 1, 3, 3)
)
elif kernel == 5:
gaussian = (
torch.tensor(
[
[1, 4, 7, 4, 1],
[4, 16, 26, 16, 4],
[7, 26, 41, 26, 7],
[4, 16, 26, 16, 4],
[1, 4, 7, 4, 1],
]
)
.float()
.to(w.device)
/ 273
)
w2 = w * gaussian
w2 = w2 / w2.sum(dim=(-1, -2), keepdims=True)
T = x_token.unfold(0, kernel, 1).unfold(1, kernel, 1)
T = (T * w2[:, :, None].to(T.device)).sum(dim=(-1, -2))
mask_full = logits < logits.mean() - mask_thr * logits.std()
mask_full[:pad, :] = False
mask_full[:, :pad] = False
mask_full[-pad:, :] = False
mask_full[:, -pad:] = False
index_tensor = torch.nonzero(mask_full.flatten()).flatten()
if len(index_tensor) == 0:
return None
rows = index_tensor // W
cols = index_tensor % W
alpha = x_token[pad:-pad, pad:-pad].norm(dim=-1).mean()
loss_neighbor = (
(x_token[rows, cols] - T[rows - pad, cols - pad]).norm(dim=-1)
).mean() / alpha
return loss_neighbor, rows, cols, T, alpha, mask_full, x_token
def get_neighbor_loss(
model,
x,
skip_less_than=1,
mask_thr=0.001,
kernel=3,
):
H = x.shape[2]
W = x.shape[3]
x = model.prepare_tokens_with_masks(x)
for i, blk in enumerate(model.blocks):
x = blk(x)
assert len(model.singular_defects) > 0
result = check_anomaly_theoretical(
x,
H // model.patch_size,
W // model.patch_size,
model.singular_defects[i],
mask_thr=mask_thr,
kernel=kernel,
)
if result is not None:
(
loss_neighbor,
rows,
cols,
T,
alpha,
mask_angle,
x_token,
) = result
if len(rows) >= skip_less_than:
assert not torch.isnan(loss_neighbor).any()
return (
i,
loss_neighbor,
rows,
cols,
T,
alpha,
mask_angle,
x_token,
)
return None
|