Skip to content

Commit 5afb8d1

Browse files
authored
Add files via upload
1 parent 4283dab commit 5afb8d1

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+13091
-0
lines changed

utils/__init__.py

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import contextlib
2+
import platform
3+
import threading
4+
5+
6+
def emojis(str=''):
7+
# Return platform-dependent emoji-safe version of string
8+
return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str
9+
10+
11+
class TryExcept(contextlib.ContextDecorator):
12+
# YOLOv5 TryExcept class. Usage: @TryExcept() decorator or 'with TryExcept():' context manager
13+
def __init__(self, msg=''):
14+
self.msg = msg
15+
16+
def __enter__(self):
17+
pass
18+
19+
def __exit__(self, exc_type, value, traceback):
20+
if value:
21+
print(emojis(f"{self.msg}{': ' if self.msg else ''}{value}"))
22+
return True
23+
24+
25+
def threaded(func):
26+
# Multi-threads a target function and returns thread. Usage: @threaded decorator
27+
def wrapper(*args, **kwargs):
28+
thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
29+
thread.start()
30+
return thread
31+
32+
return wrapper
33+
34+
35+
def join_threads(verbose=False):
36+
# Join all daemon threads, i.e. atexit.register(lambda: join_threads())
37+
main_thread = threading.current_thread()
38+
for t in threading.enumerate():
39+
if t is not main_thread:
40+
if verbose:
41+
print(f'Joining thread {t.name}')
42+
t.join()
43+
44+
45+
def notebook_init(verbose=True):
46+
# Check system software and hardware
47+
print('Checking setup...')
48+
49+
import os
50+
import shutil
51+
52+
from utils.general import check_font, check_requirements, is_colab
53+
from utils.torch_utils import select_device # imports
54+
55+
check_font()
56+
57+
import psutil
58+
from IPython import display # to display images and clear console output
59+
60+
if is_colab():
61+
shutil.rmtree('/content/sample_data', ignore_errors=True) # remove colab /sample_data directory
62+
63+
# System info
64+
if verbose:
65+
gb = 1 << 30 # bytes to GiB (1024 ** 3)
66+
ram = psutil.virtual_memory().total
67+
total, used, free = shutil.disk_usage("/")
68+
display.clear_output()
69+
s = f'({os.cpu_count()} CPUs, {ram / gb:.1f} GB RAM, {(total - free) / gb:.1f}/{total / gb:.1f} GB disk)'
70+
else:
71+
s = ''
72+
73+
select_device(newline=False)
74+
print(emojis(f'Setup complete ✅ {s}'))
75+
return display

utils/activations.py

+98
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import torch
2+
import torch.nn as nn
3+
import torch.nn.functional as F
4+
5+
6+
class SiLU(nn.Module):
7+
# SiLU activation https://arxiv.org/pdf/1606.08415.pdf
8+
@staticmethod
9+
def forward(x):
10+
return x * torch.sigmoid(x)
11+
12+
13+
class Hardswish(nn.Module):
14+
# Hard-SiLU activation
15+
@staticmethod
16+
def forward(x):
17+
# return x * F.hardsigmoid(x) # for TorchScript and CoreML
18+
return x * F.hardtanh(x + 3, 0.0, 6.0) / 6.0 # for TorchScript, CoreML and ONNX
19+
20+
21+
class Mish(nn.Module):
22+
# Mish activation https://github.com/digantamisra98/Mish
23+
@staticmethod
24+
def forward(x):
25+
return x * F.softplus(x).tanh()
26+
27+
28+
class MemoryEfficientMish(nn.Module):
29+
# Mish activation memory-efficient
30+
class F(torch.autograd.Function):
31+
32+
@staticmethod
33+
def forward(ctx, x):
34+
ctx.save_for_backward(x)
35+
return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
36+
37+
@staticmethod
38+
def backward(ctx, grad_output):
39+
x = ctx.saved_tensors[0]
40+
sx = torch.sigmoid(x)
41+
fx = F.softplus(x).tanh()
42+
return grad_output * (fx + x * sx * (1 - fx * fx))
43+
44+
def forward(self, x):
45+
return self.F.apply(x)
46+
47+
48+
class FReLU(nn.Module):
49+
# FReLU activation https://arxiv.org/abs/2007.11824
50+
def __init__(self, c1, k=3): # ch_in, kernel
51+
super().__init__()
52+
self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
53+
self.bn = nn.BatchNorm2d(c1)
54+
55+
def forward(self, x):
56+
return torch.max(x, self.bn(self.conv(x)))
57+
58+
59+
class AconC(nn.Module):
60+
r""" ACON activation (activate or not)
61+
AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
62+
according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
63+
"""
64+
65+
def __init__(self, c1):
66+
super().__init__()
67+
self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
68+
self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
69+
self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))
70+
71+
def forward(self, x):
72+
dpx = (self.p1 - self.p2) * x
73+
return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x
74+
75+
76+
class MetaAconC(nn.Module):
77+
r""" ACON activation (activate or not)
78+
MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network
79+
according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
80+
"""
81+
82+
def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r
83+
super().__init__()
84+
c2 = max(r, c1 // r)
85+
self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
86+
self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
87+
self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)
88+
self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True)
89+
# self.bn1 = nn.BatchNorm2d(c2)
90+
# self.bn2 = nn.BatchNorm2d(c1)
91+
92+
def forward(self, x):
93+
y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
94+
# batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891
95+
# beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable
96+
beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed
97+
dpx = (self.p1 - self.p2) * x
98+
return dpx * torch.sigmoid(beta * dpx) + self.p2 * x

0 commit comments

Comments
 (0)