quadra 0.0.1__py3-none-any.whl → 2.2.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (302) hide show
  1. hydra_plugins/quadra_searchpath_plugin.py +30 -0
  2. quadra/__init__.py +6 -0
  3. quadra/callbacks/__init__.py +0 -0
  4. quadra/callbacks/anomalib.py +289 -0
  5. quadra/callbacks/lightning.py +501 -0
  6. quadra/callbacks/mlflow.py +291 -0
  7. quadra/callbacks/scheduler.py +69 -0
  8. quadra/configs/__init__.py +0 -0
  9. quadra/configs/backbone/caformer_m36.yaml +8 -0
  10. quadra/configs/backbone/caformer_s36.yaml +8 -0
  11. quadra/configs/backbone/convnextv2_base.yaml +8 -0
  12. quadra/configs/backbone/convnextv2_femto.yaml +8 -0
  13. quadra/configs/backbone/convnextv2_tiny.yaml +8 -0
  14. quadra/configs/backbone/dino_vitb8.yaml +12 -0
  15. quadra/configs/backbone/dino_vits8.yaml +12 -0
  16. quadra/configs/backbone/dinov2_vitb14.yaml +12 -0
  17. quadra/configs/backbone/dinov2_vits14.yaml +12 -0
  18. quadra/configs/backbone/efficientnet_b0.yaml +8 -0
  19. quadra/configs/backbone/efficientnet_b1.yaml +8 -0
  20. quadra/configs/backbone/efficientnet_b2.yaml +8 -0
  21. quadra/configs/backbone/efficientnet_b3.yaml +8 -0
  22. quadra/configs/backbone/efficientnetv2_s.yaml +8 -0
  23. quadra/configs/backbone/levit_128s.yaml +8 -0
  24. quadra/configs/backbone/mnasnet0_5.yaml +9 -0
  25. quadra/configs/backbone/resnet101.yaml +8 -0
  26. quadra/configs/backbone/resnet18.yaml +8 -0
  27. quadra/configs/backbone/resnet18_ssl.yaml +8 -0
  28. quadra/configs/backbone/resnet50.yaml +8 -0
  29. quadra/configs/backbone/smp.yaml +9 -0
  30. quadra/configs/backbone/tiny_vit_21m_224.yaml +9 -0
  31. quadra/configs/backbone/unetr.yaml +15 -0
  32. quadra/configs/backbone/vit16_base.yaml +9 -0
  33. quadra/configs/backbone/vit16_small.yaml +9 -0
  34. quadra/configs/backbone/vit16_tiny.yaml +9 -0
  35. quadra/configs/backbone/xcit_tiny_24_p8_224.yaml +9 -0
  36. quadra/configs/callbacks/all.yaml +45 -0
  37. quadra/configs/callbacks/default.yaml +34 -0
  38. quadra/configs/callbacks/default_anomalib.yaml +64 -0
  39. quadra/configs/config.yaml +33 -0
  40. quadra/configs/core/default.yaml +11 -0
  41. quadra/configs/datamodule/base/anomaly.yaml +16 -0
  42. quadra/configs/datamodule/base/classification.yaml +21 -0
  43. quadra/configs/datamodule/base/multilabel_classification.yaml +23 -0
  44. quadra/configs/datamodule/base/segmentation.yaml +18 -0
  45. quadra/configs/datamodule/base/segmentation_multiclass.yaml +20 -0
  46. quadra/configs/datamodule/base/sklearn_classification.yaml +23 -0
  47. quadra/configs/datamodule/base/sklearn_classification_patch.yaml +17 -0
  48. quadra/configs/datamodule/base/ssl.yaml +21 -0
  49. quadra/configs/datamodule/generic/imagenette/classification/base.yaml +9 -0
  50. quadra/configs/datamodule/generic/imagenette/ssl/base.yaml +10 -0
  51. quadra/configs/datamodule/generic/mnist/anomaly/base.yaml +14 -0
  52. quadra/configs/datamodule/generic/mvtec/anomaly/base.yaml +14 -0
  53. quadra/configs/datamodule/generic/oxford_pet/segmentation/base.yaml +9 -0
  54. quadra/configs/experiment/base/anomaly/cfa.yaml +47 -0
  55. quadra/configs/experiment/base/anomaly/cflow.yaml +47 -0
  56. quadra/configs/experiment/base/anomaly/csflow.yaml +48 -0
  57. quadra/configs/experiment/base/anomaly/draem.yaml +51 -0
  58. quadra/configs/experiment/base/anomaly/efficient_ad.yaml +43 -0
  59. quadra/configs/experiment/base/anomaly/fastflow.yaml +46 -0
  60. quadra/configs/experiment/base/anomaly/inference.yaml +21 -0
  61. quadra/configs/experiment/base/anomaly/padim.yaml +37 -0
  62. quadra/configs/experiment/base/anomaly/patchcore.yaml +37 -0
  63. quadra/configs/experiment/base/classification/classification.yaml +73 -0
  64. quadra/configs/experiment/base/classification/classification_evaluation.yaml +25 -0
  65. quadra/configs/experiment/base/classification/multilabel_classification.yaml +41 -0
  66. quadra/configs/experiment/base/classification/sklearn_classification.yaml +27 -0
  67. quadra/configs/experiment/base/classification/sklearn_classification_patch.yaml +25 -0
  68. quadra/configs/experiment/base/classification/sklearn_classification_patch_test.yaml +18 -0
  69. quadra/configs/experiment/base/classification/sklearn_classification_test.yaml +25 -0
  70. quadra/configs/experiment/base/segmentation/smp.yaml +30 -0
  71. quadra/configs/experiment/base/segmentation/smp_evaluation.yaml +17 -0
  72. quadra/configs/experiment/base/segmentation/smp_multiclass.yaml +26 -0
  73. quadra/configs/experiment/base/segmentation/smp_multiclass_evaluation.yaml +18 -0
  74. quadra/configs/experiment/base/ssl/barlow.yaml +48 -0
  75. quadra/configs/experiment/base/ssl/byol.yaml +43 -0
  76. quadra/configs/experiment/base/ssl/dino.yaml +46 -0
  77. quadra/configs/experiment/base/ssl/linear_eval.yaml +52 -0
  78. quadra/configs/experiment/base/ssl/simclr.yaml +48 -0
  79. quadra/configs/experiment/base/ssl/simsiam.yaml +53 -0
  80. quadra/configs/experiment/custom/cls.yaml +12 -0
  81. quadra/configs/experiment/default.yaml +15 -0
  82. quadra/configs/experiment/generic/imagenette/classification/default.yaml +20 -0
  83. quadra/configs/experiment/generic/imagenette/ssl/barlow.yaml +14 -0
  84. quadra/configs/experiment/generic/imagenette/ssl/byol.yaml +14 -0
  85. quadra/configs/experiment/generic/imagenette/ssl/dino.yaml +14 -0
  86. quadra/configs/experiment/generic/imagenette/ssl/simclr.yaml +14 -0
  87. quadra/configs/experiment/generic/imagenette/ssl/simsiam.yaml +14 -0
  88. quadra/configs/experiment/generic/mnist/anomaly/cfa.yaml +34 -0
  89. quadra/configs/experiment/generic/mnist/anomaly/cflow.yaml +33 -0
  90. quadra/configs/experiment/generic/mnist/anomaly/csflow.yaml +33 -0
  91. quadra/configs/experiment/generic/mnist/anomaly/draem.yaml +33 -0
  92. quadra/configs/experiment/generic/mnist/anomaly/fastflow.yaml +29 -0
  93. quadra/configs/experiment/generic/mnist/anomaly/inference.yaml +27 -0
  94. quadra/configs/experiment/generic/mnist/anomaly/padim.yaml +37 -0
  95. quadra/configs/experiment/generic/mnist/anomaly/patchcore.yaml +37 -0
  96. quadra/configs/experiment/generic/mvtec/anomaly/cfa.yaml +34 -0
  97. quadra/configs/experiment/generic/mvtec/anomaly/cflow.yaml +33 -0
  98. quadra/configs/experiment/generic/mvtec/anomaly/csflow.yaml +33 -0
  99. quadra/configs/experiment/generic/mvtec/anomaly/draem.yaml +33 -0
  100. quadra/configs/experiment/generic/mvtec/anomaly/efficient_ad.yaml +38 -0
  101. quadra/configs/experiment/generic/mvtec/anomaly/fastflow.yaml +29 -0
  102. quadra/configs/experiment/generic/mvtec/anomaly/inference.yaml +27 -0
  103. quadra/configs/experiment/generic/mvtec/anomaly/padim.yaml +37 -0
  104. quadra/configs/experiment/generic/mvtec/anomaly/patchcore.yaml +37 -0
  105. quadra/configs/experiment/generic/oxford_pet/segmentation/smp.yaml +27 -0
  106. quadra/configs/export/default.yaml +13 -0
  107. quadra/configs/hydra/anomaly_custom.yaml +15 -0
  108. quadra/configs/hydra/default.yaml +14 -0
  109. quadra/configs/inference/default.yaml +26 -0
  110. quadra/configs/logger/comet.yaml +10 -0
  111. quadra/configs/logger/csv.yaml +5 -0
  112. quadra/configs/logger/mlflow.yaml +12 -0
  113. quadra/configs/logger/tensorboard.yaml +8 -0
  114. quadra/configs/loss/asl.yaml +7 -0
  115. quadra/configs/loss/barlow.yaml +2 -0
  116. quadra/configs/loss/bce.yaml +1 -0
  117. quadra/configs/loss/byol.yaml +1 -0
  118. quadra/configs/loss/cross_entropy.yaml +1 -0
  119. quadra/configs/loss/dino.yaml +8 -0
  120. quadra/configs/loss/simclr.yaml +2 -0
  121. quadra/configs/loss/simsiam.yaml +1 -0
  122. quadra/configs/loss/smp_ce.yaml +3 -0
  123. quadra/configs/loss/smp_dice.yaml +2 -0
  124. quadra/configs/loss/smp_dice_multiclass.yaml +2 -0
  125. quadra/configs/loss/smp_mcc.yaml +2 -0
  126. quadra/configs/loss/vicreg.yaml +5 -0
  127. quadra/configs/model/anomalib/cfa.yaml +35 -0
  128. quadra/configs/model/anomalib/cflow.yaml +30 -0
  129. quadra/configs/model/anomalib/csflow.yaml +34 -0
  130. quadra/configs/model/anomalib/dfm.yaml +19 -0
  131. quadra/configs/model/anomalib/draem.yaml +29 -0
  132. quadra/configs/model/anomalib/efficient_ad.yaml +31 -0
  133. quadra/configs/model/anomalib/fastflow.yaml +32 -0
  134. quadra/configs/model/anomalib/padim.yaml +32 -0
  135. quadra/configs/model/anomalib/patchcore.yaml +36 -0
  136. quadra/configs/model/barlow.yaml +16 -0
  137. quadra/configs/model/byol.yaml +25 -0
  138. quadra/configs/model/classification.yaml +10 -0
  139. quadra/configs/model/dino.yaml +26 -0
  140. quadra/configs/model/logistic_regression.yaml +4 -0
  141. quadra/configs/model/multilabel_classification.yaml +9 -0
  142. quadra/configs/model/simclr.yaml +18 -0
  143. quadra/configs/model/simsiam.yaml +24 -0
  144. quadra/configs/model/smp.yaml +4 -0
  145. quadra/configs/model/smp_multiclass.yaml +4 -0
  146. quadra/configs/model/vicreg.yaml +16 -0
  147. quadra/configs/optimizer/adam.yaml +5 -0
  148. quadra/configs/optimizer/adamw.yaml +3 -0
  149. quadra/configs/optimizer/default.yaml +4 -0
  150. quadra/configs/optimizer/lars.yaml +8 -0
  151. quadra/configs/optimizer/sgd.yaml +4 -0
  152. quadra/configs/scheduler/default.yaml +5 -0
  153. quadra/configs/scheduler/rop.yaml +5 -0
  154. quadra/configs/scheduler/step.yaml +3 -0
  155. quadra/configs/scheduler/warmrestart.yaml +2 -0
  156. quadra/configs/scheduler/warmup.yaml +6 -0
  157. quadra/configs/task/anomalib/cfa.yaml +5 -0
  158. quadra/configs/task/anomalib/cflow.yaml +5 -0
  159. quadra/configs/task/anomalib/csflow.yaml +5 -0
  160. quadra/configs/task/anomalib/draem.yaml +5 -0
  161. quadra/configs/task/anomalib/efficient_ad.yaml +5 -0
  162. quadra/configs/task/anomalib/fastflow.yaml +5 -0
  163. quadra/configs/task/anomalib/inference.yaml +3 -0
  164. quadra/configs/task/anomalib/padim.yaml +5 -0
  165. quadra/configs/task/anomalib/patchcore.yaml +5 -0
  166. quadra/configs/task/classification.yaml +6 -0
  167. quadra/configs/task/classification_evaluation.yaml +6 -0
  168. quadra/configs/task/default.yaml +1 -0
  169. quadra/configs/task/segmentation.yaml +9 -0
  170. quadra/configs/task/segmentation_evaluation.yaml +3 -0
  171. quadra/configs/task/sklearn_classification.yaml +13 -0
  172. quadra/configs/task/sklearn_classification_patch.yaml +11 -0
  173. quadra/configs/task/sklearn_classification_patch_test.yaml +8 -0
  174. quadra/configs/task/sklearn_classification_test.yaml +8 -0
  175. quadra/configs/task/ssl.yaml +2 -0
  176. quadra/configs/trainer/lightning_cpu.yaml +36 -0
  177. quadra/configs/trainer/lightning_gpu.yaml +35 -0
  178. quadra/configs/trainer/lightning_gpu_bf16.yaml +36 -0
  179. quadra/configs/trainer/lightning_gpu_fp16.yaml +36 -0
  180. quadra/configs/trainer/lightning_multigpu.yaml +37 -0
  181. quadra/configs/trainer/sklearn_classification.yaml +7 -0
  182. quadra/configs/transforms/byol.yaml +47 -0
  183. quadra/configs/transforms/byol_no_random_resize.yaml +61 -0
  184. quadra/configs/transforms/default.yaml +37 -0
  185. quadra/configs/transforms/default_numpy.yaml +24 -0
  186. quadra/configs/transforms/default_resize.yaml +22 -0
  187. quadra/configs/transforms/dino.yaml +63 -0
  188. quadra/configs/transforms/linear_eval.yaml +18 -0
  189. quadra/datamodules/__init__.py +20 -0
  190. quadra/datamodules/anomaly.py +180 -0
  191. quadra/datamodules/base.py +375 -0
  192. quadra/datamodules/classification.py +1003 -0
  193. quadra/datamodules/generic/__init__.py +0 -0
  194. quadra/datamodules/generic/imagenette.py +144 -0
  195. quadra/datamodules/generic/mnist.py +81 -0
  196. quadra/datamodules/generic/mvtec.py +58 -0
  197. quadra/datamodules/generic/oxford_pet.py +163 -0
  198. quadra/datamodules/patch.py +190 -0
  199. quadra/datamodules/segmentation.py +742 -0
  200. quadra/datamodules/ssl.py +140 -0
  201. quadra/datasets/__init__.py +17 -0
  202. quadra/datasets/anomaly.py +287 -0
  203. quadra/datasets/classification.py +241 -0
  204. quadra/datasets/patch.py +138 -0
  205. quadra/datasets/segmentation.py +239 -0
  206. quadra/datasets/ssl.py +110 -0
  207. quadra/losses/__init__.py +0 -0
  208. quadra/losses/classification/__init__.py +6 -0
  209. quadra/losses/classification/asl.py +83 -0
  210. quadra/losses/classification/focal.py +320 -0
  211. quadra/losses/classification/prototypical.py +148 -0
  212. quadra/losses/ssl/__init__.py +17 -0
  213. quadra/losses/ssl/barlowtwins.py +47 -0
  214. quadra/losses/ssl/byol.py +37 -0
  215. quadra/losses/ssl/dino.py +129 -0
  216. quadra/losses/ssl/hyperspherical.py +45 -0
  217. quadra/losses/ssl/idmm.py +50 -0
  218. quadra/losses/ssl/simclr.py +67 -0
  219. quadra/losses/ssl/simsiam.py +30 -0
  220. quadra/losses/ssl/vicreg.py +76 -0
  221. quadra/main.py +49 -0
  222. quadra/metrics/__init__.py +3 -0
  223. quadra/metrics/segmentation.py +251 -0
  224. quadra/models/__init__.py +0 -0
  225. quadra/models/base.py +151 -0
  226. quadra/models/classification/__init__.py +8 -0
  227. quadra/models/classification/backbones.py +149 -0
  228. quadra/models/classification/base.py +92 -0
  229. quadra/models/evaluation.py +322 -0
  230. quadra/modules/__init__.py +0 -0
  231. quadra/modules/backbone.py +30 -0
  232. quadra/modules/base.py +312 -0
  233. quadra/modules/classification/__init__.py +3 -0
  234. quadra/modules/classification/base.py +327 -0
  235. quadra/modules/ssl/__init__.py +17 -0
  236. quadra/modules/ssl/barlowtwins.py +59 -0
  237. quadra/modules/ssl/byol.py +172 -0
  238. quadra/modules/ssl/common.py +285 -0
  239. quadra/modules/ssl/dino.py +186 -0
  240. quadra/modules/ssl/hyperspherical.py +206 -0
  241. quadra/modules/ssl/idmm.py +98 -0
  242. quadra/modules/ssl/simclr.py +73 -0
  243. quadra/modules/ssl/simsiam.py +68 -0
  244. quadra/modules/ssl/vicreg.py +67 -0
  245. quadra/optimizers/__init__.py +4 -0
  246. quadra/optimizers/lars.py +153 -0
  247. quadra/optimizers/sam.py +127 -0
  248. quadra/schedulers/__init__.py +3 -0
  249. quadra/schedulers/base.py +44 -0
  250. quadra/schedulers/warmup.py +127 -0
  251. quadra/tasks/__init__.py +24 -0
  252. quadra/tasks/anomaly.py +582 -0
  253. quadra/tasks/base.py +397 -0
  254. quadra/tasks/classification.py +1263 -0
  255. quadra/tasks/patch.py +492 -0
  256. quadra/tasks/segmentation.py +389 -0
  257. quadra/tasks/ssl.py +560 -0
  258. quadra/trainers/README.md +3 -0
  259. quadra/trainers/__init__.py +0 -0
  260. quadra/trainers/classification.py +179 -0
  261. quadra/utils/__init__.py +0 -0
  262. quadra/utils/anomaly.py +112 -0
  263. quadra/utils/classification.py +618 -0
  264. quadra/utils/deprecation.py +31 -0
  265. quadra/utils/evaluation.py +474 -0
  266. quadra/utils/export.py +585 -0
  267. quadra/utils/imaging.py +32 -0
  268. quadra/utils/logger.py +15 -0
  269. quadra/utils/mlflow.py +98 -0
  270. quadra/utils/model_manager.py +320 -0
  271. quadra/utils/models.py +523 -0
  272. quadra/utils/patch/__init__.py +15 -0
  273. quadra/utils/patch/dataset.py +1433 -0
  274. quadra/utils/patch/metrics.py +449 -0
  275. quadra/utils/patch/model.py +153 -0
  276. quadra/utils/patch/visualization.py +217 -0
  277. quadra/utils/resolver.py +42 -0
  278. quadra/utils/segmentation.py +31 -0
  279. quadra/utils/tests/__init__.py +0 -0
  280. quadra/utils/tests/fixtures/__init__.py +1 -0
  281. quadra/utils/tests/fixtures/dataset/__init__.py +39 -0
  282. quadra/utils/tests/fixtures/dataset/anomaly.py +124 -0
  283. quadra/utils/tests/fixtures/dataset/classification.py +406 -0
  284. quadra/utils/tests/fixtures/dataset/imagenette.py +53 -0
  285. quadra/utils/tests/fixtures/dataset/segmentation.py +161 -0
  286. quadra/utils/tests/fixtures/models/__init__.py +3 -0
  287. quadra/utils/tests/fixtures/models/anomaly.py +89 -0
  288. quadra/utils/tests/fixtures/models/classification.py +45 -0
  289. quadra/utils/tests/fixtures/models/segmentation.py +33 -0
  290. quadra/utils/tests/helpers.py +70 -0
  291. quadra/utils/tests/models.py +27 -0
  292. quadra/utils/utils.py +525 -0
  293. quadra/utils/validator.py +115 -0
  294. quadra/utils/visualization.py +422 -0
  295. quadra/utils/vit_explainability.py +349 -0
  296. quadra-2.2.7.dist-info/LICENSE +201 -0
  297. quadra-2.2.7.dist-info/METADATA +381 -0
  298. quadra-2.2.7.dist-info/RECORD +300 -0
  299. {quadra-0.0.1.dist-info → quadra-2.2.7.dist-info}/WHEEL +1 -1
  300. quadra-2.2.7.dist-info/entry_points.txt +3 -0
  301. quadra-0.0.1.dist-info/METADATA +0 -14
  302. quadra-0.0.1.dist-info/RECORD +0 -4
@@ -0,0 +1,349 @@
1
+ # Original Author: jacobgil
2
+ # Title: Explainability for Vision Transformers
3
+ # Source: https://github.com/jacobgil/vit-explain (MIT license)
4
+ # Description: This is a heavily modified version of the original jacobgil code (the underlying math is still the same).
5
+ from __future__ import annotations
6
+
7
+ import math
8
+
9
+ import numpy as np
10
+ import torch
11
+ from sklearn.linear_model._base import LinearClassifierMixin
12
+
13
+
14
+ def rollout(
15
+ attentions: list[torch.Tensor], discard_ratio: float = 0.9, head_fusion: str = "mean", aspect_ratio: float = 1.0
16
+ ) -> np.ndarray:
17
+ """Apply rollout on Attention matrices.
18
+
19
+ Args:
20
+ attentions: List of Attention matrices coming from different blocks
21
+ discard_ratio: Percentage of elements to discard
22
+ head_fusion: Strategy of fusion of attention heads
23
+ aspect_ratio: Model inputs' width divided by height
24
+
25
+ Returns:
26
+ mask: Output mask, still needs a resize
27
+ """
28
+ result = torch.eye(attentions[0].size(-1))
29
+ with torch.no_grad():
30
+ for attention in attentions:
31
+ if head_fusion == "mean":
32
+ attention_heads_fused = attention.mean(dim=1)
33
+ elif head_fusion == "max":
34
+ attention_heads_fused = attention.max(dim=1)[0]
35
+ elif head_fusion == "min":
36
+ attention_heads_fused = attention.min(dim=1)[0]
37
+ else:
38
+ raise ValueError("Attention head fusion type Not supported")
39
+ # Drop the lowest attentions, but
40
+ # don't drop the class token
41
+ flat = attention_heads_fused.view(attention_heads_fused.size(0), -1)
42
+ _, indices = flat.topk(int(flat.size(-1) * discard_ratio), -1, False)
43
+ flat.scatter_(-1, indices, 0)
44
+ identity_matrix = torch.eye(attention_heads_fused.size(-1))
45
+ a = (attention_heads_fused + 1.0 * identity_matrix) / 2
46
+ a = a / a.sum(dim=-1).unsqueeze(1)
47
+ result = torch.matmul(a, result)
48
+ # Look at the total attention between the class token and the image patches
49
+ mask = result[:, 0, 1:]
50
+ batch_size = mask.size(0)
51
+ # TODO: Non squared input-size handling can be improved. Not easy though
52
+ height = math.floor((mask.size(-1) / aspect_ratio) ** 0.5)
53
+ total_size = mask.size(-1)
54
+ width = math.floor(total_size / height)
55
+ if mask.size(-1) > (height * width):
56
+ to_remove = mask.size(-1) - (height * width)
57
+ mask = mask[:, :-to_remove]
58
+ mask = mask.reshape(batch_size, height, width).numpy()
59
+ mask = mask / mask.max(axis=(1, 2), keepdims=True)
60
+
61
+ return mask
62
+
63
+
64
+ class VitAttentionRollout:
65
+ """Attention gradient rollout class. Constructor registers hooks to the model's specified layers.
66
+ Only 4 layers by default given the high load on gpu. Best gradcams obtained using all blocks.
67
+
68
+ Args:
69
+ model: Model
70
+ attention_layer_names: On which layers to register the hook
71
+ head_fusion: Strategy of fusion for attention heads
72
+ discard_ratio: Percentage of elements to discard
73
+ """
74
+
75
+ def __init__(
76
+ self,
77
+ model: torch.nn.Module,
78
+ attention_layer_names: list[str] | None = None,
79
+ head_fusion: str = "mean",
80
+ discard_ratio: float = 0.9,
81
+ ):
82
+ if attention_layer_names is None:
83
+ attention_layer_names = [
84
+ "blocks.6.attn.attn_drop",
85
+ "blocks.7.attn.attn_drop",
86
+ "blocks.10.attn.attn_drop",
87
+ "blocks.11.attn.attn_drop",
88
+ ]
89
+ self.model = model
90
+ self.head_fusion = head_fusion
91
+ self.discard_ratio = discard_ratio
92
+ self.f_hook_handles: list[torch.utils.hooks.RemovableHandle] = []
93
+ for name, module in self.model.named_modules():
94
+ for layer_name in attention_layer_names:
95
+ if layer_name in name:
96
+ self.f_hook_handles.append(module.register_forward_hook(self.get_attention))
97
+ self.attentions: list[torch.Tensor] = []
98
+
99
+ # pylint: disable=unused-argument
100
+ def get_attention(
101
+ self,
102
+ module: torch.nn.Module,
103
+ inpt: torch.Tensor,
104
+ out: torch.Tensor,
105
+ ) -> None:
106
+ """Hook to return attention.
107
+
108
+ Args:
109
+ module: Torch module
110
+ inpt: Input tensor
111
+ out: Output tensor, in this case the attention
112
+ """
113
+ self.attentions.append(out.detach().clone().cpu())
114
+
115
+ def __call__(self, input_tensor: torch.Tensor) -> np.ndarray:
116
+ """Called when the class instance is used as a function.
117
+
118
+ Args:
119
+ input_tensor: Input tensor
120
+
121
+ Returns:
122
+ out: Batch of output masks
123
+ """
124
+ self.attentions.clear()
125
+ with torch.no_grad():
126
+ self.model(input_tensor)
127
+ out = rollout(
128
+ self.attentions,
129
+ self.discard_ratio,
130
+ self.head_fusion,
131
+ aspect_ratio=(input_tensor.shape[-1] / input_tensor.shape[-2]),
132
+ )
133
+
134
+ return out
135
+
136
+
137
+ ############################################### GRAD ROLLOUT ##########################################################
138
+
139
+
140
+ def grad_rollout(
141
+ attentions: list[torch.Tensor], gradients: list[torch.Tensor], discard_ratio: float = 0.9, aspect_ratio: float = 1.0
142
+ ) -> np.ndarray:
143
+ """Apply gradient rollout on Attention matrices.
144
+
145
+ Args:
146
+ attentions: Attention matrices
147
+ gradients: Target class gradient matrices
148
+ discard_ratio: Percentage of elements to discard
149
+ aspect_ratio: Model inputs' width divided by height
150
+
151
+ Returns:
152
+ mask: Output mask, still needs a resize
153
+ """
154
+ result = torch.eye(attentions[0].size(-1))
155
+ with torch.no_grad():
156
+ for attention, grad in zip(attentions, gradients):
157
+ weights = grad
158
+ attention_heads_fused = torch.mean((attention * weights), dim=1)
159
+ attention_heads_fused[attention_heads_fused < 0] = 0
160
+ # Drop the lowest attentions, but
161
+ # don't drop the class token
162
+ flat = attention_heads_fused.view(attention_heads_fused.size(0), -1)
163
+ _, indices = flat.topk(int(flat.size(-1) * discard_ratio), -1, False)
164
+ flat.scatter_(-1, indices, 0)
165
+ I = torch.eye(attention_heads_fused.size(-1))
166
+ a = (attention_heads_fused + 1.0 * I) / 2
167
+ a = a / a.sum(dim=-1).unsqueeze(1)
168
+ result = torch.matmul(a, result)
169
+ # Look at the total attention between the class token,
170
+ # and the image patches
171
+ mask = result[:, 0, 1:]
172
+ batch_size = mask.size(0)
173
+ # TODO: Non squared input-size handling can be improved. Not easy though
174
+ height = math.floor((mask.size(-1) / aspect_ratio) ** 0.5)
175
+ total_size = mask.size(-1)
176
+ width = math.floor(total_size / height)
177
+ if mask.size(-1) > (height * width):
178
+ to_remove = mask.size(-1) - (height * width)
179
+ mask = mask[:, :-to_remove]
180
+ mask = mask.reshape(batch_size, height, width).numpy()
181
+ mask = mask / mask.max(axis=(1, 2), keepdims=True)
182
+
183
+ return mask
184
+
185
+
186
+ class VitAttentionGradRollout:
187
+ """Attention gradient rollout class. Constructor registers hooks to the model's specified layers.
188
+ Only 4 layers by default given the high load on gpu. Best gradcams obtained using all blocks.
189
+
190
+ Args:
191
+ model: Pytorch model
192
+ attention_layer_names: On which layers to register the hooks
193
+ discard_ratio: Percentage of elements to discard
194
+ classifier: Scikit-learn classifier. Leave it to None if model already has a classifier on top.
195
+ """
196
+
197
+ def __init__( # pylint: disable=W0102
198
+ self,
199
+ model: torch.nn.Module,
200
+ attention_layer_names: list[str] | None = None,
201
+ discard_ratio: float = 0.9,
202
+ classifier: LinearClassifierMixin | None = None,
203
+ example_input: torch.Tensor | None = None,
204
+ ):
205
+ if attention_layer_names is None:
206
+ attention_layer_names = [
207
+ "blocks.6.attn.attn_drop",
208
+ "blocks.7.attn.attn_drop",
209
+ "blocks.10.attn.attn_drop",
210
+ "blocks.11.attn.attn_drop",
211
+ ]
212
+
213
+ if classifier is not None:
214
+ if example_input is None:
215
+ raise ValueError(
216
+ "Must provide an input example to LinearModelPytorchWrapper when classifier is not None"
217
+ )
218
+ self.model = LinearModelPytorchWrapper(
219
+ backbone=model,
220
+ linear_classifier=classifier,
221
+ example_input=example_input,
222
+ device=next(model.parameters()).device,
223
+ )
224
+ else:
225
+ self.model = model # type: ignore[assignment]
226
+
227
+ self.discard_ratio = discard_ratio
228
+ self.f_hook_handles: list[torch.utils.hooks.RemovableHandle] = []
229
+ self.b_hook_handles: list[torch.utils.hooks.RemovableHandle] = []
230
+ for name, module in self.model.named_modules():
231
+ for layer_name in attention_layer_names:
232
+ if layer_name in name:
233
+ self.f_hook_handles.append(module.register_forward_hook(self.get_attention))
234
+ self.b_hook_handles.append(module.register_backward_hook(self.get_attention_gradient))
235
+ self.attentions: list[torch.Tensor] = []
236
+ self.attention_gradients: list[torch.Tensor] = []
237
+ # Activate gradients
238
+ blocks_list = [x.split("blocks")[1].split(".attn")[0] for x in attention_layer_names]
239
+ for name, module in model.named_modules():
240
+ for p in module.parameters():
241
+ if "blocks" in name and any(x in name for x in blocks_list):
242
+ p.requires_grad = True
243
+
244
+ # pylint: disable=unused-argument
245
+ def get_attention(
246
+ self,
247
+ module: torch.nn.Module,
248
+ inpt: torch.Tensor,
249
+ out: torch.Tensor,
250
+ ) -> None:
251
+ """Hook to return attention.
252
+
253
+ Args:
254
+ module: Torch module
255
+ inpt: Input tensor
256
+ out: Output tensor, in this case the attention
257
+ """
258
+ self.attentions.append(out.detach().clone().cpu())
259
+
260
+ # pylint: disable=unused-argument
261
+ def get_attention_gradient(
262
+ self,
263
+ module: torch.nn.Module,
264
+ grad_input: torch.Tensor,
265
+ grad_output: torch.Tensor,
266
+ ) -> None:
267
+ """Hook to return attention.
268
+
269
+ Args:
270
+ module: Torch module
271
+ grad_input: Gradients' input tensor
272
+ grad_output: Gradients' output tensor, in this case the attention
273
+ """
274
+ self.attention_gradients.append(grad_input[0].detach().clone().cpu())
275
+
276
+ def __call__(self, input_tensor: torch.Tensor, targets_list: list[int]) -> np.ndarray:
277
+ """Called when the class instance is used as a function.
278
+
279
+ Args:
280
+ input_tensor: Model's input tensor
281
+ targets_list: List of targets. If None, argmax is used
282
+
283
+ Returns:
284
+ out: Batch of output masks
285
+ """
286
+ self.attentions.clear()
287
+ self.attention_gradients.clear()
288
+
289
+ self.model.zero_grad(set_to_none=True)
290
+ self.model.to(input_tensor.device)
291
+ output = self.model(input_tensor).cpu()
292
+
293
+ class_mask = torch.zeros(output.shape)
294
+ if targets_list is None:
295
+ targets_list = output.argmax(dim=1)
296
+ class_mask[torch.arange(output.shape[0]), targets_list] = 1
297
+ loss = (output * class_mask).sum()
298
+ loss.backward()
299
+ out = grad_rollout(
300
+ self.attentions,
301
+ self.attention_gradients,
302
+ self.discard_ratio,
303
+ aspect_ratio=(input_tensor.shape[-1] / input_tensor.shape[-2]),
304
+ )
305
+
306
+ return out
307
+
308
+
309
+ class LinearModelPytorchWrapper(torch.nn.Module):
310
+ """Pytorch wrapper for scikit-learn linear models.
311
+
312
+ Args:
313
+ backbone: Backbone
314
+ linear_classifier: ScikitLearn linear classifier model
315
+ example_input: Input example needed to obtain output shape
316
+ device: The device to use. Defaults to "cpu"
317
+ """
318
+
319
+ def __init__(
320
+ self,
321
+ backbone: torch.nn.Module,
322
+ linear_classifier: LinearClassifierMixin,
323
+ example_input: torch.Tensor,
324
+ device: torch.device,
325
+ ):
326
+ super().__init__()
327
+ self.device = device
328
+ self.backbone = backbone.to(device)
329
+ if not isinstance(linear_classifier, LinearClassifierMixin):
330
+ raise TypeError("Classifier is not of type LinearClassifierMixin.")
331
+ self.num_classes = len(linear_classifier.classes_)
332
+ self.linear_classifier = linear_classifier
333
+ with torch.no_grad():
334
+ output = self.backbone(example_input.to(device))
335
+ num_filters = output.shape[-1]
336
+
337
+ self.classifier = torch.nn.Linear(num_filters, self.num_classes).to(device)
338
+ self.classifier.weight.data = torch.from_numpy(linear_classifier.coef_).float()
339
+ self.classifier.bias.data = torch.from_numpy(linear_classifier.intercept_).float()
340
+
341
+ def forward(self, x):
342
+ if self.num_classes == 2:
343
+ class_one_probabilities = torch.nn.Sigmoid()(self.classifier(self.backbone(x)))
344
+ class_zero_probabilities = 1 - class_one_probabilities
345
+ two_class_probs = torch.cat((class_zero_probabilities, class_one_probabilities), dim=1)
346
+
347
+ return two_class_probs
348
+
349
+ return torch.nn.Softmax(dim=1)(self.classifier(self.backbone(x)))
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2023] Orobix Srl
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.