models
AttentionExtractor(model, attention_layer_name='attn_drop')
¶
Bases: Module
General attention extractor.
Parameters:
-
model
(
Module
) –Backbone model which contains the attention layer. attention_layer_name: Attention layer for extracting attention maps. Defaults to "attn_drop".
-
attention_layer_name
(
str
, default:'attn_drop'
) –Attention layer for extracting attention maps.
Source code in quadra/utils/models.py
312 313 314 315 316 317 318 |
|
clear()
¶
Clear the grabbed attentions.
Source code in quadra/utils/models.py
320 321 322 |
|
get_attention(module, input_tensor, output)
¶
Method to be registered to grab attentions.
Source code in quadra/utils/models.py
324 325 326 |
|
process_attention_maps(attentions, img_width, img_height)
staticmethod
¶
Preprocess attentions maps to be visualized.
Parameters:
-
attentions
(
Tensor
) –grabbed attentions
-
img_width
(
int
) –image width
-
img_height
(
int
) –image height
Returns:
-
Tensor
–torch.Tensor: preprocessed attentions, with the shape equal to the one of the image from
-
Tensor
–which attentions has been computed
Source code in quadra/utils/models.py
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 |
|
L2Norm
¶
Bases: Module
Compute L2 Norm.
LSABlock(dim, num_heads, mlp_ratio=4.0, qkv_bias=False, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=torch.nn.GELU, norm_layer=torch.nn.LayerNorm, mask_diagonal=True, learnable_temperature=True)
¶
Bases: Module
Local Self Attention Block from https://arxiv.org/abs/2112.13492.
Parameters:
-
dim
(
int
) –embedding dimension
-
num_heads
(
int
) –number of attention heads
-
mlp_ratio
(
float
, default:4.0
) –ratio of mlp hidden dim to embedding dim
-
qkv_bias
(
bool
, default:False
) –enable bias for qkv if True
-
drop
(
float
, default:0.0
) –dropout rate
-
attn_drop
(
float
, default:0.0
) –attention dropout rate
-
drop_path
(
float
, default:0.0
) –stochastic depth rate
-
act_layer
(
type[Module]
, default:GELU
) –activation layer
-
norm_layer
(
type[LayerNorm]
, default:LayerNorm
) –: normalization layer
-
mask_diagonal
(
bool
, default:True
) –whether to mask Q^T x K diagonal with -infinity so not to count self relationship between tokens. Defaults to True
-
learnable_temperature
(
bool
, default:True
) –whether to use a learnable temperature as specified in https://arxiv.org/abs/2112.13492. Defaults to True.
Source code in quadra/utils/models.py
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
|
LocalSelfAttention(dim, num_heads=8, qkv_bias=False, attn_drop=0.0, proj_drop=0.0, mask_diagonal=True, learnable_temperature=True)
¶
Bases: Module
Local Self Attention from https://arxiv.org/abs/2112.13492.
Parameters:
-
dim
(
int
) –embedding dimension.
-
num_heads
(
int
, default:8
) –number of attention heads.
-
qkv_bias
(
bool
, default:False
) –enable bias for qkv if True.
-
attn_drop
(
float
, default:0.0
) –attention dropout rate.
-
proj_drop
(
float
, default:0.0
) –projection dropout rate.
-
mask_diagonal
(
bool
, default:True
) –whether to mask Q^T x K diagonal with -infinity so not to count self relationship between tokens. Defaults to True.
-
learnable_temperature
(
bool
, default:True
) –whether to use a learnable temperature as specified in https://arxiv.org/abs/2112.13492. Defaults to True.
Source code in quadra/utils/models.py
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
|
forward(x)
¶
Computes the local self attention.
Parameters:
-
x
(
Tensor
) –input tensor
Returns:
-
Tensor
–Output of the local self attention.
Source code in quadra/utils/models.py
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 |
|
PositionalEncoding1D(d_model, temperature=10000.0, dropout=0.0, max_len=5000)
¶
Bases: Module
Standard sine-cosine positional encoding from https://arxiv.org/abs/2010.11929.
Parameters:
-
d_model
(
int
) –Embedding dimension
-
temperature
(
float
, default:10000.0
) –Temperature for the positional encoding. Defaults to 10000.0.
-
dropout
(
float
, default:0.0
) –Dropout rate. Defaults to 0.0.
-
max_len
(
int
, default:5000
) –Maximum length of the sequence. Defaults to 5000.
Source code in quadra/utils/models.py
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 |
|
forward(x)
¶
Forward pass of the positional encoding.
Parameters:
-
x
(
Tensor
) –torch tensor [batch_size, seq_len, embedding_dim].
Source code in quadra/utils/models.py
396 397 398 399 400 401 402 403 |
|
clip_gradients(model, clip)
¶
Parameters:
-
model
(
Module
) –The model
-
clip
(
float
) –The clip value.
Returns:
Source code in quadra/utils/models.py
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
|
create_net_hat(dims, act_fun=torch.nn.ReLU, dropout_p=0)
¶
Create a sequence of linear layers with activation functions and dropout.
Parameters:
-
dims
(
list[int]
) –Dimension of hidden layers and output
-
act_fun
(
Callable
, default:ReLU
) –activation function to use between layers, default ReLU
-
dropout_p
(
float
, default:0
) –Dropout probability. Defaults to 0.
Returns:
-
Sequential
–Sequence of linear layers of dimension specified by the input, each linear layer is followed by an activation function and optionally a dropout layer with the input probability
Source code in quadra/utils/models.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
|
get_feature(feature_extractor, dl, iteration_over_training=1, gradcam=False, classifier=None, input_shape=None, limit_batches=None)
¶
Given a dataloader and a PyTorch model, extract features with the model and return features and labels.
Parameters:
-
dl
(
DataLoader
) –PyTorch dataloader
-
feature_extractor
(
Module | BaseEvaluationModel
) –Pretrained PyTorch backbone
-
iteration_over_training
(
int
, default:1
) –Extract feature iteration_over_training times for each image (best if used with augmentation)
-
gradcam
(
bool
, default:False
) –Whether to compute gradcams. Notice that it will slow the function
-
classifier
(
ClassifierMixin | None
, default:None
) –Scikit-learn classifier
-
input_shape
(
tuple[int, int, int] | None
, default:None
) –[H,W,C], backbone input shape, needed by classifier's pytorch wrapper
-
limit_batches
(
int | None
, default:None
) –Limit the number of batches to be processed
Returns:
-
tuple[ndarray, ndarray, ndarray | None]
–Tuple containing: features: Model features labels: input_labels grayscale_cams: Gradcam output maps, None if gradcam arg is False
Source code in quadra/utils/models.py
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 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
|
init_weights(m)
¶
Basic weight initialization.
Source code in quadra/utils/models.py
76 77 78 79 80 81 82 83 84 85 86 87 |
|
is_vision_transformer(model)
¶
Verify if pytorch module is a Vision Transformer. This check is primarily needed for gradcam computation in classification tasks.
Parameters:
-
model
(
Module
) –Model
Source code in quadra/utils/models.py
208 209 210 211 212 213 214 215 |
|
net_hat(input_size, output_size)
¶
Create a linear layer with input and output neurons.
Parameters:
Returns:
-
Sequential
–A sequential containing a single Linear layer taking input neurons and producing output neurons
Source code in quadra/utils/models.py
32 33 34 35 36 37 38 39 40 41 42 43 |
|
trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0)
¶
Call _no_grad_trunc_normal_
with torch.no_grad()
.
Parameters:
-
tensor
(
Tensor
) –an n-dimensional
torch.Tensor
-
mean
(
float
, default:0.0
) –the mean of the normal distribution
-
std
(
float
, default:1.0
) –the standard deviation of the normal distribution
-
a
(
float
, default:-2.0
) –the minimum cutoff
-
b
(
float
, default:2.0
) –the maximum cutoff
Source code in quadra/utils/models.py
267 268 269 270 271 272 273 274 275 276 277 |
|