henry000 commited on
Commit
6e3c0d5
·
1 Parent(s): de05146

🔨 [Add] helper function - auto padding & act func

Browse files
Files changed (1) hide show
  1. yolo/tools/module_helper.py +36 -0
yolo/tools/module_helper.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple
2
+
3
+ from torch import nn
4
+ from torch.nn.common_types import _size_2_t
5
+
6
+
7
+ def auto_pad(kernel_size: _size_2_t, dilation: _size_2_t = 1, **kwargs) -> Tuple[int, int]:
8
+ """
9
+ Auto Padding for the convolution blocks
10
+ """
11
+ if isinstance(kernel_size, int):
12
+ kernel_size = (kernel_size, kernel_size)
13
+ if isinstance(dilation, int):
14
+ dilation = (dilation, dilation)
15
+
16
+ pad_h = ((kernel_size[0] - 1) * dilation[0]) // 2
17
+ pad_w = ((kernel_size[1] - 1) * dilation[1]) // 2
18
+ return (pad_h, pad_w)
19
+
20
+
21
+ def get_activation(activation: str) -> nn.Module:
22
+ """
23
+ Retrieves an activation function from the PyTorch nn module based on its name, case-insensitively.
24
+ """
25
+ if not activation or activation.lower() in ["false", "none"]:
26
+ return nn.Identity()
27
+
28
+ activation_map = {
29
+ name.lower(): obj
30
+ for name, obj in nn.modules.activation.__dict__.items()
31
+ if isinstance(obj, type) and issubclass(obj, nn.Module)
32
+ }
33
+ if activation.lower() in activation_map:
34
+ return activation_map[activation.lower()]()
35
+ else:
36
+ raise ValueError(f"Activation function '{activation}' is not found in torch.nn")