-
Notifications
You must be signed in to change notification settings - Fork 248
/
Copy path(ECCV 2024)HTB.py
210 lines (168 loc) · 8.17 KB
/
(ECCV 2024)HTB.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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
206
207
208
209
210
# 论文:Restoring Images in Adverse Weather Conditions via Histogram Transformer (ECCV 2024)
# 论文地址:https://arxiv.org/pdf/2407.10172
# 全网最全100➕即插即用模块GitHub地址:https://github.com/ai-dawang/PlugNPlay-Modules
import numbers
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
Conv2d = nn.Conv2d
##########################################################################
## Layer Norm
def to_2d(x):
return rearrange(x, 'b c h w -> b (h w c)')
def to_3d(x):
# return rearrange(x, 'b c h w -> b c (h w)')
return rearrange(x, 'b c h w -> b (h w) c')
def to_4d(x,h,w):
# return rearrange(x, 'b c (h w) -> b c h w',h=h,w=w)
return rearrange(x, 'b (h w) c -> b c h w',h=h,w=w)
class BiasFree_LayerNorm(nn.Module):
def __init__(self, normalized_shape):
super(BiasFree_LayerNorm, self).__init__()
if isinstance(normalized_shape, numbers.Integral):
normalized_shape = (normalized_shape,)
normalized_shape = torch.Size(normalized_shape)
assert len(normalized_shape) == 1
self.normalized_shape = normalized_shape
def forward(self, x):
sigma = x.var(-1, keepdim=True, unbiased=False)
return x / torch.sqrt(sigma+1e-5) #* self.weight
class WithBias_LayerNorm(nn.Module):
def __init__(self, normalized_shape):
super(WithBias_LayerNorm, self).__init__()
if isinstance(normalized_shape, numbers.Integral):
normalized_shape = (normalized_shape,)
normalized_shape = torch.Size(normalized_shape)
assert len(normalized_shape) == 1
self.normalized_shape = normalized_shape
def forward(self, x):
mu = x.mean(-1, keepdim=True)
sigma = x.var(-1, keepdim=True, unbiased=False)
return (x - mu) / torch.sqrt(sigma+1e-5) #* self.weight + self.bias
class LayerNorm(nn.Module):
def __init__(self, dim, LayerNorm_type="WithBias"):
super(LayerNorm, self).__init__()
if LayerNorm_type =='BiasFree':
self.body = BiasFree_LayerNorm(dim)
else:
self.body = WithBias_LayerNorm(dim)
def forward(self, x):
h, w = x.shape[-2:]
return to_4d(self.body(to_3d(x)), h, w)
##########################################################################
## Dual-scale Gated Feed-Forward Network (DGFF)
class FeedForward(nn.Module):
def __init__(self, dim, ffn_expansion_factor, bias):
super(FeedForward, self).__init__()
hidden_features = int(dim * ffn_expansion_factor)
self.project_in = Conv2d(dim, hidden_features * 2, kernel_size=1, bias=bias)
self.dwconv_5 = Conv2d(hidden_features // 4, hidden_features // 4, kernel_size=5, stride=1, padding=2,
groups=hidden_features // 4, bias=bias)
self.dwconv_dilated2_1 = Conv2d(hidden_features // 4, hidden_features // 4, kernel_size=3, stride=1, padding=2,
groups=hidden_features // 4, bias=bias, dilation=2)
self.p_unshuffle = nn.PixelUnshuffle(2)
self.p_shuffle = nn.PixelShuffle(2)
self.project_out = Conv2d(hidden_features, dim, kernel_size=1, bias=bias)
def forward(self, x):
x = self.project_in(x)
x = self.p_shuffle(x)
x1, x2 = x.chunk(2, dim=1)
x1 = self.dwconv_5(x1)
x2 = self.dwconv_dilated2_1(x2)
x = F.mish(x2) * x1
x = self.p_unshuffle(x)
x = self.project_out(x)
return x
##########################################################################
##Dynamic-range Histogram Self-Attention (DHSA)
class Attention_histogram(nn.Module):
def __init__(self, dim, num_heads=4, bias=False, ifBox=True):
super(Attention_histogram, self).__init__()
self.factor = num_heads
self.ifBox = ifBox
self.num_heads = num_heads
self.temperature = nn.Parameter(torch.ones(num_heads, 1, 1))
self.qkv = Conv2d(dim, dim * 5, kernel_size=1, bias=bias)
self.qkv_dwconv = Conv2d(dim * 5, dim * 5, kernel_size=3, stride=1, padding=1, groups=dim * 5, bias=bias)
self.project_out = Conv2d(dim, dim, kernel_size=1, bias=bias)
def pad(self, x, factor):
hw = x.shape[-1]
t_pad = [0, 0] if hw % factor == 0 else [0, (hw // factor + 1) * factor - hw]
x = F.pad(x, t_pad, 'constant', 0)
return x, t_pad
def unpad(self, x, t_pad):
_, _, hw = x.shape
return x[:, :, t_pad[0]:hw - t_pad[1]]
def softmax_1(self, x, dim=-1):
logit = x.exp()
logit = logit / (logit.sum(dim, keepdim=True) + 1)
return logit
def normalize(self, x):
mu = x.mean(-2, keepdim=True)
sigma = x.var(-2, keepdim=True, unbiased=False)
return (x - mu) / torch.sqrt(sigma + 1e-5) # * self.weight + self.bias
def reshape_attn(self, q, k, v, ifBox):
b, c = q.shape[:2]
q, t_pad = self.pad(q, self.factor)
k, t_pad = self.pad(k, self.factor)
v, t_pad = self.pad(v, self.factor)
hw = q.shape[-1] // self.factor
shape_ori = "b (head c) (factor hw)" if ifBox else "b (head c) (hw factor)"
shape_tar = "b head (c factor) hw"
q = rearrange(q, '{} -> {}'.format(shape_ori, shape_tar), factor=self.factor, hw=hw, head=self.num_heads)
k = rearrange(k, '{} -> {}'.format(shape_ori, shape_tar), factor=self.factor, hw=hw, head=self.num_heads)
v = rearrange(v, '{} -> {}'.format(shape_ori, shape_tar), factor=self.factor, hw=hw, head=self.num_heads)
q = torch.nn.functional.normalize(q, dim=-1)
k = torch.nn.functional.normalize(k, dim=-1)
attn = (q @ k.transpose(-2, -1)) * self.temperature
attn = self.softmax_1(attn, dim=-1)
out = (attn @ v)
out = rearrange(out, '{} -> {}'.format(shape_tar, shape_ori), factor=self.factor, hw=hw, b=b,
head=self.num_heads)
out = self.unpad(out, t_pad)
return out
def forward(self, x):
b, c, h, w = x.shape
x_sort, idx_h = x[:, :c // 2].sort(-2)
x_sort, idx_w = x_sort.sort(-1)
x[:, :c // 2] = x_sort
qkv = self.qkv_dwconv(self.qkv(x))
q1, k1, q2, k2, v = qkv.chunk(5, dim=1) # b,c,x,x
v, idx = v.view(b, c, -1).sort(dim=-1)
q1 = torch.gather(q1.view(b, c, -1), dim=2, index=idx)
k1 = torch.gather(k1.view(b, c, -1), dim=2, index=idx)
q2 = torch.gather(q2.view(b, c, -1), dim=2, index=idx)
k2 = torch.gather(k2.view(b, c, -1), dim=2, index=idx)
out1 = self.reshape_attn(q1, k1, v, True)
out2 = self.reshape_attn(q2, k2, v, False)
out1 = torch.scatter(out1, 2, idx, out1).view(b, c, h, w)
out2 = torch.scatter(out2, 2, idx, out2).view(b, c, h, w)
out = out1 * out2
out = self.project_out(out)
out_replace = out[:, :c // 2]
out_replace = torch.scatter(out_replace, -1, idx_w, out_replace)
out_replace = torch.scatter(out_replace, -2, idx_h, out_replace)
out[:, :c // 2] = out_replace
return out
##########################################################################
##Histogram Transformer Block (HTB)
class TransformerBlock(nn.Module):
def __init__(self, dim, num_heads=4, ffn_expansion_factor=2.5, bias=False, LayerNorm_type='WithBias'):## Other option 'BiasFree'
super(TransformerBlock, self).__init__()
self.attn_g = Attention_histogram(dim, num_heads, bias, True)
self.norm_g = LayerNorm(dim, LayerNorm_type)
self.ffn = FeedForward(dim, ffn_expansion_factor, bias)
self.norm_ff1 = LayerNorm(dim, LayerNorm_type)
def forward(self, x):
x = x + self.attn_g(self.norm_g(x))
x_out = x + self.ffn(self.norm_ff1(x))
return x_out
if __name__ == '__main__':
input = torch.randn(1, 64, 128, 128)#输入 B C H W
transformer_block = TransformerBlock(64)#输入C
# 前向传播
output = transformer_block(input)
# 打印输入和输出的形状
print(input.size())
print(output.size())