Skip to content

Commit 0cdcbd4

Browse files
authored
Add files via upload
Signed-off-by: Bubbles The Dev <[email protected]>
1 parent f61d79d commit 0cdcbd4

Some content is hidden

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

50 files changed

+9178
-0
lines changed

Export-Models/utils/__init__.py

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

Export-Models/utils/activations.py

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

0 commit comments

Comments
 (0)