File size: 26,751 Bytes
5528edf | 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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 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 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import ops
from basicsr.utils.registry import ARCH_REGISTRY
from einops import rearrange
from basicsr.archs.arch_util import trunc_normal_
from itertools import repeat
import collections.abc
from typing import Tuple
from pdb import set_trace as st
import numpy as np
f"""
cust_arch.py
"""
# df2k download : https://github.com/dslisleedh/Download_df2k/blob/main/download_df2k.sh
# dataset prepare : https://github.com/XPixelGroup/BasicSR/blob/master/docs/DatasetPreparation.md
####################################################
## LN and ConvFFN
class LayerNorm(nn.Module):
def __init__(self, normalized_shape, eps=1e-6, channel_first=True):
super().__init__()
self.channel_first = channel_first
self.normalized_shape = normalized_shape
self.eps = eps
self.norm = nn.LayerNorm(normalized_shape, eps=eps)
def forward(self, x):
if self.channel_first == False:
return self.norm(x)
elif self.channel_first == True:
x = x.permute(0, 2, 3, 1)
x = self.norm(x)
x = x.permute(0, 3, 1, 2)
return x
class dwconv(nn.Module):
def __init__(self, hidden_features, kernel_size=5):
super(dwconv, self).__init__()
self.depthwise_conv = nn.Conv2d(
hidden_features, hidden_features,
kernel_size=kernel_size, stride=1,
padding=(kernel_size - 1) // 2,
groups=hidden_features,
)
def forward(self, x, x_size):
# x: [B, L, C]
B, L, C = x.shape
H, W = x_size
x = x.transpose(1, 2).reshape(B, C, H, W)
x = self.depthwise_conv(x)
x = x.view(B, C, -1).transpose(1, 2)
return x
class ConvFFN(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, kernel_size=5):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.dwconv = dwconv(hidden_features=hidden_features, kernel_size=kernel_size)
self.fc2 = nn.Linear(hidden_features, out_features)
self.act = nn.GELU()
def forward(self, x, x_size):
x = self.fc1(x)
x = self.act(x)
x = x + self.dwconv(x, x_size)
x = self.fc2(x)
return x
##############################################################
## Inter-Window Attn
class CUSTAttention(nn.Module):
def __init__(self,
dim,
window_size=8,
group_size=9):
super().__init__()
### var
self.window_size = window_size # 8 -> 64
self.group_size = group_size # 9 -> 81
self.scale = dim ** -0.5
hidden_dim = dim
self.to_q = nn.Linear(dim, hidden_dim)
self.to_k = nn.Linear(dim, hidden_dim)
self.to_v = nn.Linear(dim, dim)
self.proj = nn.Linear(dim, dim)
# gate before proj
self.gate_proj = nn.Linear(dim, dim)
self.act = nn.Sigmoid()
############ window group partition and reverse Start ############
def window_group_partition(self, x):
B, C, H, W = x.shape
ws, gs = self.window_size, self.group_size
####################
# Pad
####################
target_unit = ws * gs
pad_h = (target_unit - H % target_unit) % target_unit
pad_w = (target_unit - W % target_unit) % target_unit
if pad_h > 0 or pad_w > 0:
x = F.pad(x, (0, pad_w, 0, pad_h), mode='reflect')
H_pad, W_pad = x.shape[2], x.shape[3]
gh, gw = H_pad // target_unit, W_pad // target_unit # ๊ฐ h, w ๋ณ ๊ทธ๋ฃน ๊ฐ์
########################################################
# Partition and Grouping
# [B C (gh gs ws) (gw gs ws)] 8์ฐจ์์ผ๋ก ํ ๋ฒ์ ์ชผ๊ฐ๊ณ
# [B gh gw gs gs ws ws C]๋ก ์ด๋.
########################################################
x = x.view(B, C, gh, gs, ws, gw, gs, ws)
x = x.permute(0, 2, 5, 3, 6, 4, 7, 1)
x = x.contiguous().view(B, gh * gw, gs * gs, ws * ws, C)
return x, pad_h, pad_w
def window_group_reverse(self, x, original_shape, padded_size):
b, ng, gs_sq, ws_sq, chan = x.shape
ws, gs = self.window_size, self.group_size
_, _, H, W = original_shape
########################
# Pad ํฌ๊ธฐ ๊ณ์ฐ
########################
H_pad, W_pad = H + padded_size[0], W + padded_size[1]
gh, gw = H_pad // (ws * gs), W_pad // (ws * gs)
##########################################################
# 8์ฐจ์์ผ๋ก ๋ณต์ ํ ์ฌ๋ฐฐ์น([b, c, (gh gs ws), (gw gs ws)])
# ์ดํ [B C H_pad W_pad]๋ก ๋ณต๊ตฌ
##########################################################
x = x.view(b, gh, gw, gs, gs, ws, ws, chan)
x = x.permute(0, 7, 1, 3, 5, 2, 4, 6)
x = x.contiguous().view(b, chan, H_pad, W_pad)
if padded_size[0] > 0 or padded_size[1] > 0:
x = x[:, :, :H, :W]
return x
############ window group partition and reverse End ############
def cana(self, x_grouped, sim):
f"""
๋ค์ ์ฒญํฌ๋ฅผ ํค/๋ฐธ๋ฅ์ ์ถ๊ฐ.
๋จ, ๋ค๋ฅธ window๋ฅผ ๋์ ์ ์ฌ๋๋ก ๊ฐ๋ ํจ์น๋ -inf ์ฒ๋ฆฌ
sim : [B, ng, gs, ws, gs] : ๊ฐ ํจ์น๋ค(ws)๊ณผ, ๊ทธ๋ฃน ๋ด์ ์๋์ฐ๋ค(gs) ๊ฐ์ ์ ์ฌ๋
"""
B, ng, gs, ws, chan = x_grouped.shape
device = x_grouped.device
x_grouped = x_grouped.view(B*ng, gs*ws, chan) # [๋ฐฐ์น*๊ทธ๋ฃน์, ๊ทธ๋ฃน์ฌ์ด์ฆ*์๋์ฐ์ฌ์ด์ฆ, ์ฑ๋]
assign_id = sim.argmax(dim=-1).view(B*ng, gs*ws)
sorting_indices = torch.argsort(assign_id, dim=1)
### x์ id๋ฅผ ์ ๋ ฌ๋ ์์๋๋ก ์ฌ๋ฐฐ์ด
gather_idx = sorting_indices.unsqueeze(-1).expand(-1, -1, chan) # [B*ng, gs*ws, C]: ์ฑ๋ ๋ฐฉํฅ์ผ๋ก expand
x_sorted = torch.gather(x_grouped, 1, gather_idx) # [B*ng, gs*ws, C]
id_sorted = torch.gather(assign_id, 1, sorting_indices) # [B*ng, gs*ws]
cs = self.window_size ** 2 # chunk_size
nc = (gs*ws) // cs # num_chunk
# A) Query
q_chunks = x_sorted.view(B * ng, nc, cs, chan)
q_ids = id_sorted.view(B * ng, nc, cs)
###########################################################################
# B-2) (์ ๋ฐ ์ฒญํฌ + ํ ์ฒญํฌ + ๋ค์ ๋ฐ ์ฒญํฌ)
pad_x = torch.zeros(B*ng, cs//2, chan, device=device)
pad_x = torch.cat([pad_x, x_sorted, pad_x], dim=1)
pad_id = torch.full((B*ng, cs//2), -1, device=device)
pad_id = torch.cat([pad_id, id_sorted, pad_id], dim=1) # [B*ng, gs*ws+64]
###########################################################################
# Unfold ํตํด ์ฌ๋ผ์ด๋ฉ ์๋์ฐ ์์ฑ(win=128, stride=64)
kv_chunks = pad_x.unfold(1, cs*2, cs).permute(0, 1, 3, 2)
kv_ids = pad_id.unfold(1, cs*2, cs) # [B*ng, 128, nc]
###############################################################################
# Attn with Masking
###############################################################################
q = self.to_q(q_chunks) # [BG, Chunks, 64, C]
k = self.to_k(kv_chunks) # [BG, Chunks, 128, C]
v = self.to_v(kv_chunks) # [BG, Chunks, 128, C]
attn = (q @ k.transpose(-2, -1)) * self.scale # [BG, Chunks, 64, 128]
### Masking ###
# Query์ ID์ Key์ ID๊ฐ ๊ฐ์ ๋๋ง True (๊ฐ์ ๊ทธ๋ฃน๋ผ๋ฆฌ๋ง)
# q_ids: [..., 64, 1], kv_ids: [..., 1, 128]
mask = (q_ids.unsqueeze(-1) == kv_ids.unsqueeze(-2))
# False์ธ ๋ถ๋ถ(ID ๋ถ์ผ์น)์ ์์๊ฐ์ผ๋ก ๋ง์คํน
min_val = -1e4
attn = attn.masked_fill(~mask, min_val)
attn = attn.softmax(dim=-1)
out = attn @ v # [b*ng, Chunks, 64, C]
gate = self.act(self.gate_proj(x_sorted)).view(B*ng, gs, ws, -1) # [B*ng, gs*ws, 1]
out = out * gate
#####################################
# Unsort & Restore(์๋ ์์๋ก ๋ณต๊ตฌ)
#####################################
out = out.view(B * ng, gs*ws, chan)
out = self.proj(out)
inverse_indices = torch.argsort(sorting_indices, dim=1)
inverse_indices = inverse_indices.unsqueeze(-1).expand(-1, -1, chan)
out = torch.gather(out, 1, inverse_indices)
out = out.view(B, ng, gs, ws, chan)
return out
def forward(self, x):
# x: [B, C, H, W]
batch, chan, H, W = x.shape
###################
# ์ด๋ฏธ์ง -> ๊ทธ๋ฃนํ๋ ์๋์ฐ ํ
์๋ก ๋ณํ([B, num_group, group_size, win_size, c]) ๋ค ํค ํ๋ง
###################
x_grouped, pad_h, pad_w = self.window_group_partition(x)
#####################################
# ์ ์ฌ๋ ๊ณ์ฐ ๋ฐ ๋ค๋ฅธ ํจ์น์ ์ฎ๊ธฐ ๊ณ์ฐ
#####################################
sim = x_grouped.detach().mean(dim=3) # [B, num_group, group_size, c]
sim = torch.einsum('b g w p c, b g k c -> b g w p k', x_grouped, sim) # [B, ng, gs, ws, gs]
cana_out = self.cana(x_grouped, sim)
#####################
# ์๋ shape๋ก ๋๋๋ฆผ
#####################
x = self.window_group_reverse(cana_out, x.shape, (pad_h, pad_w))
return x
class CUSTBlock(nn.Module):
def __init__(self,
dim,
window_size=8,
group_size=9,
ffn_scale=2.0,):
super().__init__()
self.pe = nn.Conv2d(dim, dim, kernel_size=3, padding=1, groups=dim)
# Attention Path
self.norm1 = LayerNorm(dim)
self.attn = CUSTAttention(dim, window_size, group_size)
# FFN Path
self.norm2 = LayerNorm(dim)
self.ffn = ConvFFN(dim, int(dim * ffn_scale))
def forward(self, x):
x = x + self.pe(x)
# 2. Attention (Pre-Norm & Residual)
x = x + self.attn(self.norm1(x))
# 3. FFN (Pre-Norm & Residual)
shortcut = x
x = self.norm2(x)
B, C, H, W = x.shape
x = rearrange(x, 'b c h w -> b (h w) c')
x = self.ffn(x, (H, W))
x = rearrange(x, 'b (h w) c -> b c h w', h=H, w=W)
x = shortcut + x
return x
##############################################################
## Intra-Window Attn
def patch_divide(x, step, ps):
"""Crop image into patches(์ด๋ฏธ์ง๋ฅผ ์ง์ ๋ ํฌ๊ธฐ(ps)๋ก ์๋ฅด๋, ์๋ก ๊ฒน์น๊ฒ ์๋ฅธ๋ค.)
Args:
x (Tensor): Input feature map of shape(b, c, h, w).
step (int): Divide step. 'ps-2'
ps (int): Patch size. [16, 20, 24, 28, 16, 20, 24, 28]
Returns:
crop_x (Tensor): Cropped patches.
nh (int): Number of patches along the horizontal direction.
nw (int): Number of patches along the vertical direction.
"""
b, c, h, w = x.size()
if h == ps and w == ps: # h==w==patch_size์ผ ๊ฒฝ์ฐ, step์ ps-2๊ฐ ์๋ ps
step = ps
crop_x = []
nh = 0
##########################################################################
# if h == 100 : range(0, 98, 14) --> i = [0, 14, 28, ... 84] ์ด๋ ๊ฒ ๋ฃจํ๋ฅผ ๋.
# top, down = (0, 16), ... (84, 100)
# down > h : ์ด๋ฏธ์ง ๋(h)๊ฐ ํจ์น ์ด๋๊ฐ๊ฒฉ(step)์ผ๋ก ๋ฑ ๋จ์ด์ง์ง ์์ ๋, ์ํฌ๋ฆฌ ๊ณต๊ฐ์ด ๋จ์ ๋ T
# h=101์ผ ๋, range(0,99,14)์ด๋ฏ๋ก i=[0,14,...98], ์ฆ i=98์ด ์ถ๊ฐ๋จ.
# ์ด ๋, down=98+16>h๋ก, ๋ฒ์๋ฅผ ๋ฒ์ด๋จ. ๊ทธ๋ฌ๋ฉด (top,down)=(85,101)๋ก, ์ด๋ฏธ์ง ๋งจ ๋์ down์ผ๋ก ๊ฐ๊ฒ ๋จ.
# right > w : ๋ง์ฐฌ๊ฐ์ง๋ก, ์ด๋ฏธ์ง ๋๋น(w)๊ฐ ํจ์น ์ด๋๊ฐ๊ฒฉ(step)์ผ๋ก ๋จ์ด์ง์ง ์์ ๋
# w=75์ผ ๋, range(0, 73, 14)์ด๋ฏ๋ก j=[0,14,...70], ์ฆ j=70์ด ์ถ๊ฐ๋จ.
# ๊ทธ๋ฌ๋ฉด right=70+16>w์ด ๋๋ฏ๋ก, (right,left) = (56,70)๋ก, ์ด๋ฏธ์ง ๋งจ ๋์ right๋ก ๊ฐ๊ฒ ๋จ.
# ์ด๋ ๊ฒ ํ๋์ ๋์ด์์ ์ฌ๋ฌ ๊ฐ์ ์ด๋ฏธ์ง๋ฅผ crop์ผ๋ก ์๋ผ๋.
# nh =์ธ๋ก๋ฐฉํฅ์ผ๋ก ์๋ผ๋ธ ๊ฐ์ / nw = ์ด ํฌ๋กญ๋ ์ด๋ฏธ์ง / ์ธ๋ก๋ก ์๋ผ๋ธ ์ = ๊ฐ๋ก๋ก ์๋ผ๋ธ ์
##########################################################################
for i in range(0, h + step - ps, step):
top = i
down = i + ps
if down > h:
top = h - ps
down = h
nh += 1
for j in range(0, w + step - ps, step):
left = j
right = j + ps
if right > w:
left = w - ps
right = w
crop_x.append(x[:, :, top:down, left:right])
nw = len(crop_x) // nh
#####################################
# crop_x : [(์ด crop๋ ํ์) x (B, dim, ps, ps)] = 42 x [B 40 16 16]
# stack ๋ฐ permute๋ก, [b 42 40 16 16]์ผ๋ก ๋ง๋ค๊ณ , nh, nw์ ํจ๊ป ๋ฐํ
#####################################
crop_x = torch.stack(crop_x, dim=0) # (n, b, c, ps, ps)
crop_x = crop_x.permute(1, 0, 2, 3, 4).contiguous() # (b, n, c, ps, ps)
return crop_x, nh, nw
def patch_reverse(crop_x, x, step, ps):
"""Reverse patches into image.
Args:
crop_x (Tensor): Cropped patches. [B, num_crop, dim, ps, ps]
x (Tensor): Feature map of shape(b, c, h, w).
step (int): Divide step.
ps (int): Patch size.
Returns:
output (Tensor): Reversed image. [B, dim(40), H, W]
"""
b, c, h, w = x.size()
output = torch.zeros_like(x)
index = 0
####################################################
# ํฌ๋กญ๋ ์ด๋ฏธ์ง๋ฅผ ์์๋๋ก ๋ค์ ์ง์ด๋ฃ๊ธฐ(output์).
# ์์๊ฐ range(crop_x[1]=num_crop)์ด ์๋,
# ์ง์ด๋ฃ์ ๊ฐ๊ฒฉ์ ๋จผ์ ์ ํ๊ณ , ๊ฑฐ๊ธฐ์ crop_x[:,index]๋ฅผ ๋ํจ
####################################################
for i in range(0, h + step - ps, step):
top = i
down = i + ps
if down > h:
top = h - ps
down = h
for j in range(0, w + step - ps, step):
left = j
right = j + ps
if right > w:
left = w - ps
right = w
output[:, :, top:down, left:right] += crop_x[:, index]
index += 1
####################################################
# patch overlap์ผ๋ก ์ธํด, ์ค์ฒฉ๋์ด 2๋ฒ ๋ํด์ง ์์ญ๋ค์ 2๋ก ๋๋.
# [height, 2]๋งํผ, ๋๋ [2, width]๋งํผ ๋ํด์ง ์์ญ์ 2๋ฒ ๋ํด์ก์.
# [2, 2] ์์ญ์ 4๋ฒ ๋ํด์ก์. ์ด๋ for๋ฌธ 2๊ฐ๋ฅผ ๋๋ฉด์ 4๋ก ๋๋ ์ง.
####################################################
for i in range(step, h + step - ps, step):
top = i
down = i + ps - step
if top + ps > h:
top = h - ps
output[:, :, top:down, :] /= 2
for j in range(step, w + step - ps, step):
left = j
right = j + ps - step
if left + ps > w:
left = w - ps
output[:, :, :, left:right] /= 2
return output
class Attention(nn.Module):
"""Attention module.
Args:
dim (int): Base channels.
heads (int): Head numbers.
qk_dim (int): Channels of query and key.
"""
def __init__(self, dim, heads, qk_dim):
super().__init__()
self.heads = heads
self.dim = dim
self.qk_dim = qk_dim
self.scale = qk_dim ** -0.5
# attn
self.qkv = nn.Linear(dim, dim*3, bias=False)
self.gate = nn.Linear(dim, dim)
self.proj = nn.Linear(dim, dim, bias=False)
self.act = nn.GELU()
self.pe = nn.Conv2d(dim, dim, kernel_size=3, padding=1, groups=dim)
def forward(self, x):
B, N, C = x.shape
ws = int(N**0.5)
qkv = self.qkv(x)
q, k, v = qkv.split([self.qk_dim, self.qk_dim, self.dim], dim=-1)
z = self.act(self.gate(x))
# attn
pe = self.pe(q.transpose(1,2).view(B, C, ws, ws)).view(B, C, N).transpose(1,2)
# q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h=self.heads), (q, k, v))
attn = (q @ k.transpose(-2, -1)) * self.scale
attn = attn.softmax(dim=-1)
out = (attn @ v) + pe
# gate
out = out * z
# out = rearrange(out, 'b h n d -> b n (h d)')
return self.proj(out)
### Frequency Modulation
class Low_to_high_MS_v2(nn.Module):
def __init__(self, dim):
super().__init__()
self.error_refiner = nn.Sequential(
nn.Conv2d(dim, dim, kernel_size=3, padding=2, dilation=2, groups=dim, bias=False),
nn.GELU(),
nn.Conv2d(dim, dim, 1)
)
self.gate_gen = nn.Sequential(
nn.Conv2d(dim * 2, dim // 4, kernel_size=1),
nn.GELU(),
nn.Conv2d(dim // 4, 1, kernel_size=1),
nn.Sigmoid()
)
self.scale = nn.Parameter(torch.zeros(1, dim, 1, 1))
def forward(self, x):
B, C, H, W = x.shape
###################################
# 1. ๊ณ์ธต์ ์ค์ฐจ ์ถ์ถ
###################################
x_d2 = F.adaptive_avg_pool2d(x, (H // 2, W // 2))
x_u2 = F.interpolate(x_d2, size=(H, W), mode='bilinear', align_corners=False)
err2 = x - x_u2
x_d4 = F.adaptive_avg_pool2d(x_d2, (H // 4, W // 4))
x_u4 = F.interpolate(x_d4, size=(H, W), mode='bilinear', align_corners=False)
err4 = x_u2 - x_u4
#################################
# 2. Refiner & Gate
#################################
refined_error = self.error_refiner(err2 + err4)
error_energies = torch.cat([err2.abs(), err4.abs()], dim=1)
spatial_gate = self.gate_gen(error_energies)
return x + (self.scale * refined_error * spatial_gate)
class MEDA(nn.Module):
"""Attention module.
Args:
dim (int): Base channels.
num (int): Number of blocks.
qk_dim (int): Channels of query and key in Attention.
mlp_dim (int): Channels of hidden mlp in Mlp.
heads (int): Head numbers of Attention.
patch_divide ๋ฐ reverse (with overlapping)์ ๋ชฉํ :
step(stride)๋ฅผ ps(patch_size)๋ณด๋ค ์๊ฒ ํด์, ๊ฒฝ๊ณ๋ฉด์ ์๋ ์ ๋ค์ ์ ๋ณด๋ฅผ ๋ ์ ํ์
ํ๊ธฐ ์ํจ.
"""
def __init__(self,
dim,
qk_dim,
ffn_scale=2.0,
heads=1):
super().__init__()
self.norm1 = LayerNorm(dim, channel_first=False)
self.norm2 = LayerNorm(dim, channel_first=False)
self.lth = Low_to_high_MS_v2(dim)
self.attn = Attention(dim, heads, qk_dim)
self.ffn = ConvFFN(dim, int(dim * ffn_scale))
def forward(self, x, ps):
B, C, H, W = x.shape
step = ps - 2
x = self.lth(x)
############################
# Patch Divide - LN - ATTN
# ps(patch_size) : [16, 20, 24, 28, 16, 20, 24, 28]
# ๋ง๋ค์ด์ง q,k,v(=[ํฌ๋กญ๋ ์ด๋ฏธ์ง ๊ฐ์xB, head, ps*ps, head_dim]) ๊ฐ์ attn ์งํ
############################
crop_x, nh, nw = patch_divide(x, step, ps) # (b, n, c, ps, ps)
b, n, c, ph, pw = crop_x.shape
crop_x = rearrange(crop_x, 'b n c h w -> (b n) (h w) c')
crop_x = self.attn(self.norm1(crop_x)) + crop_x
crop_x = rearrange(crop_x, '(b n) (h w) c -> b n c h w', n=n, w=pw)
################################
# Patch Reverse - LN - MLP(ConvFFN)
# patch_reverse input : crop_x, x(์ฒซ input), step(=patch_size - 2), ps)
################################
x = patch_reverse(crop_x, x, step, ps)
_, _, h, w = x.shape
x = rearrange(x, 'b c h w-> b (h w) c')
x = self.ffn(self.norm2(x), x_size=(h, w)) + x
x = rearrange(x, 'b (h w) c->b c h w', h=h)
return x
##############################################################
## Block
class MainBlock(nn.Module):
def __init__(self,
dim,
ffn_scale=2.0,
drop=0.,
attn_drop=0.,
drop_path=0.,
patch_size=16,
window_size=8,
group_size=9,):
super().__init__()
self.patch_size = patch_size
### Multiscale Block
self.cust = CUSTBlock(dim,
ffn_scale=ffn_scale,
window_size=window_size,
group_size=group_size,)
self.meda = MEDA(dim,
dim, # qk_dim
ffn_scale=ffn_scale,
)
### Feedforward layer
self.mid_conv = nn.Conv2d(dim, dim, 3, 1, 1)
def forward(self, x):
residual = x
x = self.cust(x)
x = self.meda(x, self.patch_size)
x = self.mid_conv(x) + residual
return x
##############################################################
## Overall Architecture
# @ARCH_REGISTRY.register()
class CUSTNet(nn.Module):
def __init__(self,
dim,
ffn_scale=2.0,
upscaling_factor=4,
drop_rate=0.,
attn_drop_rate=0.,
drop_path_rate=0.,
patch_size=[12, 16, 20, 24, 12, 16, 20, 24],
window_size=8,
group_size=10,):
super().__init__()
self.to_feat = nn.Conv2d(3, dim, 3, 1, 1)
self.dim = dim
n_blocks = len(patch_size)
self.pos_drop = nn.Dropout(p=drop_rate)
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, n_blocks)] # stochastic depth decay rule
self.feats = nn.Sequential(*[MainBlock(dim,
ffn_scale,
drop=drop_rate,
attn_drop=attn_drop_rate,
drop_path=dpr[i],
patch_size=patch_size[i],
window_size=window_size,
group_size=group_size,
)
for i in range(n_blocks)])
# self.to_img = nn.Sequential(
# nn.Conv2d(dim, 3 * upscaling_factor**2, 3, 1, 1),
# nn.PixelShuffle(upscaling_factor)
#)
self.upscale = upscaling_factor
if self.upscale == 4:
self.upconv1 = nn.Conv2d(self.dim, self.dim * 4, 3, 1, 1, bias=True)
self.upconv2 = nn.Conv2d(self.dim, self.dim * 4, 3, 1, 1, bias=True)
self.pixel_shuffle = nn.PixelShuffle(2)
elif self.upscale == 2 or self.upscale == 3:
self.upconv = nn.Conv2d(self.dim, self.dim * (self.upscale ** 2), 3, 1, 1, bias=True)
self.pixel_shuffle = nn.PixelShuffle(self.upscale)
self.last_conv = nn.Conv2d(self.dim, 3, 3, 1, 1)
if self.upscale != 1:
self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)
self.apply(self._init_weights)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
def check_img_size(self, x):
_, _, h, w = x.size()
downsample_scale = 8
scaled_size = self.window_size * downsample_scale
mod_pad_h = (scaled_size - h % scaled_size) % scaled_size
mod_pad_w = (scaled_size - w % scaled_size) % scaled_size
x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), 'reflect')
return x
def forward(self, x):
B, C, H, W = x.shape
# patch embed
x_feat = self.to_feat(x)
# module, and return to original shape
x_feat = self.feats(x_feat) + x_feat
x_feat = x_feat[:, :, :H, :W]
## reconstruction
if self.upscale == 4:
x_feat = self.lrelu(self.pixel_shuffle(self.upconv1(x_feat)))
x_feat = self.lrelu(self.pixel_shuffle(self.upconv2(x_feat)))
elif self.upscale == 1:
x_feat = x_feat
else:
x_feat = self.lrelu(self.pixel_shuffle(self.upconv(x_feat)))
x_feat = self.last_conv(x_feat)
if self.upscale != 1:
base = F.interpolate(x, scale_factor=self.upscale, mode='bilinear', align_corners=False)
else:
base = x
x_out = x_feat + base
return x_out
if __name__== '__main__':
#############Test Model Complexity #############
from fvcore.nn import flop_count_table, FlopCountAnalysis, ActivationCountAnalysis
# x, upscaling_factor = torch.randn(1, 3, 640, 360), 2
# x, upscaling_factor = torch.randn(1, 3, 427, 240), 3
x, upscaling_factor = torch.randn(1, 3, 320, 180), 4
# x = torch.randn(1, 3, 256, 256)
window_size, group_size = 8, 10
# large
# patch_size = [12,14,16,18,12,14,16,18,12,14,16,18]
# branch_dim = [40]
# tiny
branch_dim = [30]
patch_size = [18,18,18,18,18,18,18,18]
dim = sum(branch_dim)
model = CUSTNet(dim=dim,
ffn_scale=2.0,
upscaling_factor=upscaling_factor,
window_size=window_size,
patch_size=patch_size,)
# print(model)
print(f'params: {sum(map(lambda x: x.numel(), model.parameters()))}')
print(flop_count_table(FlopCountAnalysis(model, x), activations=ActivationCountAnalysis(model, x)))
# output = model(x)
# print(output.shape)
|