Spaces:
Running
on
Zero
Running
on
Zero
File size: 15,900 Bytes
0b23d5a |
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 |
import torch
import torch.nn as nn
from collections import OrderedDict
from extralibs.cond_api import ExtraCondition
from core.modules.x_transformer import FixedPositionalEmbedding
from core.basics import zero_module, conv_nd, avg_pool_nd
class Downsample(nn.Module):
"""
A downsampling layer with an optional convolution.
:param channels: channels in the inputs and outputs.
:param use_conv: a bool determining if a convolution is applied.
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
downsampling occurs in the inner-two dimensions.
"""
def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
super().__init__()
self.channels = channels
self.out_channels = out_channels or channels
self.use_conv = use_conv
self.dims = dims
stride = 2 if dims != 3 else (1, 2, 2)
if use_conv:
self.op = conv_nd(
dims,
self.channels,
self.out_channels,
3,
stride=stride,
padding=padding,
)
else:
assert self.channels == self.out_channels
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
def forward(self, x):
assert x.shape[1] == self.channels
return self.op(x)
class ResnetBlock(nn.Module):
def __init__(self, in_c, out_c, down, ksize=3, sk=False, use_conv=True):
super().__init__()
ps = ksize // 2
if in_c != out_c or sk == False:
self.in_conv = nn.Conv2d(in_c, out_c, ksize, 1, ps)
else:
self.in_conv = None
self.block1 = nn.Conv2d(out_c, out_c, 3, 1, 1)
self.act = nn.ReLU()
self.block2 = nn.Conv2d(out_c, out_c, ksize, 1, ps)
if sk == False:
self.skep = nn.Conv2d(in_c, out_c, ksize, 1, ps)
else:
self.skep = None
self.down = down
if self.down == True:
self.down_opt = Downsample(in_c, use_conv=use_conv)
def forward(self, x):
if self.down == True:
x = self.down_opt(x)
if self.in_conv is not None:
x = self.in_conv(x)
h = self.block1(x)
h = self.act(h)
h = self.block2(h)
if self.skep is not None:
return h + self.skep(x)
else:
return h + x
class Adapter(nn.Module):
def __init__(
self,
channels=[320, 640, 1280, 1280],
nums_rb=3,
cin=64,
ksize=3,
sk=True,
use_conv=True,
stage_downscale=True,
use_identity=False,
):
super(Adapter, self).__init__()
if use_identity:
self.inlayer = nn.Identity()
else:
self.inlayer = nn.PixelUnshuffle(8)
self.channels = channels
self.nums_rb = nums_rb
self.body = []
for i in range(len(channels)):
for j in range(nums_rb):
if (i != 0) and (j == 0):
self.body.append(
ResnetBlock(
channels[i - 1],
channels[i],
down=stage_downscale,
ksize=ksize,
sk=sk,
use_conv=use_conv,
)
)
else:
self.body.append(
ResnetBlock(
channels[i],
channels[i],
down=False,
ksize=ksize,
sk=sk,
use_conv=use_conv,
)
)
self.body = nn.ModuleList(self.body)
self.conv_in = nn.Conv2d(cin, channels[0], 3, 1, 1)
def forward(self, x):
# unshuffle
x = self.inlayer(x)
# extract features
features = []
x = self.conv_in(x)
for i in range(len(self.channels)):
for j in range(self.nums_rb):
idx = i * self.nums_rb + j
x = self.body[idx](x)
features.append(x)
return features
class PositionNet(nn.Module):
def __init__(self, input_size=(40, 64), cin=4, dim=512, out_dim=1024):
super().__init__()
self.input_size = input_size
self.out_dim = out_dim
self.down_factor = 8 # determined by the convnext backbone
feature_dim = dim
self.backbone = Adapter(
channels=[64, 128, 256, feature_dim],
nums_rb=2,
cin=cin,
stage_downscale=True,
use_identity=True,
)
self.num_tokens = (self.input_size[0] // self.down_factor) * (
self.input_size[1] // self.down_factor
)
self.pos_embedding = nn.Parameter(
torch.empty(1, self.num_tokens, feature_dim).normal_(std=0.02)
) # from BERT
self.linears = nn.Sequential(
nn.Linear(feature_dim, 512),
nn.SiLU(),
nn.Linear(512, 512),
nn.SiLU(),
nn.Linear(512, out_dim),
)
# self.null_feature = torch.nn.Parameter(torch.zeros([feature_dim]))
def forward(self, x, mask=None):
B = x.shape[0]
# token from edge map
# x = torch.nn.functional.interpolate(x, self.input_size)
feature = self.backbone(x)[-1]
objs = feature.reshape(B, -1, self.num_tokens)
objs = objs.permute(0, 2, 1) # N*Num_tokens*dim
"""
# expand null token
null_objs = self.null_feature.view(1,1,-1)
null_objs = null_objs.repeat(B,self.num_tokens,1)
# mask replacing
mask = mask.view(-1,1,1)
objs = objs*mask + null_objs*(1-mask)
"""
# add pos
objs = objs + self.pos_embedding
# fuse them
objs = self.linears(objs)
assert objs.shape == torch.Size([B, self.num_tokens, self.out_dim])
return objs
class PositionNet2(nn.Module):
def __init__(self, input_size=(40, 64), cin=4, dim=320, out_dim=1024):
super().__init__()
self.input_size = input_size
self.out_dim = out_dim
self.down_factor = 8 # determined by the convnext backbone
self.dim = dim
self.backbone = Adapter(
channels=[dim, dim, dim, dim],
nums_rb=2,
cin=cin,
stage_downscale=True,
use_identity=True,
)
self.pos_embedding = FixedPositionalEmbedding(dim=self.dim)
self.linears = nn.Sequential(
nn.Linear(dim, 512),
nn.SiLU(),
nn.Linear(512, 512),
nn.SiLU(),
nn.Linear(512, out_dim),
)
def forward(self, x, mask=None):
B = x.shape[0]
features = self.backbone(x)
token_lists = []
for feature in features:
objs = feature.reshape(B, self.dim, -1)
objs = objs.permute(0, 2, 1) # N*Num_tokens*dim
# add pos
objs = objs + self.pos_embedding(objs)
# fuse them
objs = self.linears(objs)
token_lists.append(objs)
return token_lists
class LayerNorm(nn.LayerNorm):
"""Subclass torch's LayerNorm to handle fp16."""
def forward(self, x: torch.Tensor):
orig_type = x.dtype
ret = super().forward(x.type(torch.float32))
return ret.type(orig_type)
class QuickGELU(nn.Module):
def forward(self, x: torch.Tensor):
return x * torch.sigmoid(1.702 * x)
class ResidualAttentionBlock(nn.Module):
def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head)
self.ln_1 = LayerNorm(d_model)
self.mlp = nn.Sequential(
OrderedDict(
[
("c_fc", nn.Linear(d_model, d_model * 4)),
("gelu", QuickGELU()),
("c_proj", nn.Linear(d_model * 4, d_model)),
]
)
)
self.ln_2 = LayerNorm(d_model)
self.attn_mask = attn_mask
def attention(self, x: torch.Tensor):
self.attn_mask = (
self.attn_mask.to(dtype=x.dtype, device=x.device)
if self.attn_mask is not None
else None
)
return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
def forward(self, x: torch.Tensor):
x = x + self.attention(self.ln_1(x))
x = x + self.mlp(self.ln_2(x))
return x
class StyleAdapter(nn.Module):
def __init__(self, width=1024, context_dim=768, num_head=8, n_layes=3, num_token=4):
super().__init__()
scale = width**-0.5
self.transformer_layes = nn.Sequential(
*[ResidualAttentionBlock(width, num_head) for _ in range(n_layes)]
)
self.num_token = num_token
self.style_embedding = nn.Parameter(torch.randn(1, num_token, width) * scale)
self.ln_post = LayerNorm(width)
self.ln_pre = LayerNorm(width)
self.proj = nn.Parameter(scale * torch.randn(width, context_dim))
def forward(self, x):
# x shape [N, HW+1, C]
style_embedding = self.style_embedding + torch.zeros(
(x.shape[0], self.num_token, self.style_embedding.shape[-1]),
device=x.device,
)
x = torch.cat([x, style_embedding], dim=1)
x = self.ln_pre(x)
x = x.permute(1, 0, 2) # NLD -> LND
x = self.transformer_layes(x)
x = x.permute(1, 0, 2) # LND -> NLD
x = self.ln_post(x[:, -self.num_token :, :])
x = x @ self.proj
return x
class ResnetBlock_light(nn.Module):
def __init__(self, in_c):
super().__init__()
self.block1 = nn.Conv2d(in_c, in_c, 3, 1, 1)
self.act = nn.ReLU()
self.block2 = nn.Conv2d(in_c, in_c, 3, 1, 1)
def forward(self, x):
h = self.block1(x)
h = self.act(h)
h = self.block2(h)
return h + x
class extractor(nn.Module):
def __init__(self, in_c, inter_c, out_c, nums_rb, down=False):
super().__init__()
self.in_conv = nn.Conv2d(in_c, inter_c, 1, 1, 0)
self.body = []
for _ in range(nums_rb):
self.body.append(ResnetBlock_light(inter_c))
self.body = nn.Sequential(*self.body)
self.out_conv = nn.Conv2d(inter_c, out_c, 1, 1, 0)
self.down = down
if self.down == True:
self.down_opt = Downsample(in_c, use_conv=False)
def forward(self, x):
if self.down == True:
x = self.down_opt(x)
x = self.in_conv(x)
x = self.body(x)
x = self.out_conv(x)
return x
class Adapter_light(nn.Module):
def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64):
super(Adapter_light, self).__init__()
self.unshuffle = nn.PixelUnshuffle(8)
self.channels = channels
self.nums_rb = nums_rb
self.body = []
for i in range(len(channels)):
if i == 0:
self.body.append(
extractor(
in_c=cin,
inter_c=channels[i] // 4,
out_c=channels[i],
nums_rb=nums_rb,
down=False,
)
)
else:
self.body.append(
extractor(
in_c=channels[i - 1],
inter_c=channels[i] // 4,
out_c=channels[i],
nums_rb=nums_rb,
down=True,
)
)
self.body = nn.ModuleList(self.body)
def forward(self, x):
# unshuffle
x = self.unshuffle(x)
# extract features
features = []
for i in range(len(self.channels)):
x = self.body[i](x)
features.append(x)
return features
class CoAdapterFuser(nn.Module):
def __init__(
self, unet_channels=[320, 640, 1280, 1280], width=768, num_head=8, n_layes=3
):
super(CoAdapterFuser, self).__init__()
scale = width**0.5
self.task_embedding = nn.Parameter(scale * torch.randn(16, width))
self.positional_embedding = nn.Parameter(
scale * torch.randn(len(unet_channels), width)
)
self.spatial_feat_mapping = nn.ModuleList()
for ch in unet_channels:
self.spatial_feat_mapping.append(
nn.Sequential(
nn.SiLU(),
nn.Linear(ch, width),
)
)
self.transformer_layes = nn.Sequential(
*[ResidualAttentionBlock(width, num_head) for _ in range(n_layes)]
)
self.ln_post = LayerNorm(width)
self.ln_pre = LayerNorm(width)
self.spatial_ch_projs = nn.ModuleList()
for ch in unet_channels:
self.spatial_ch_projs.append(zero_module(nn.Linear(width, ch)))
self.seq_proj = nn.Parameter(torch.zeros(width, width))
def forward(self, features):
if len(features) == 0:
return None, None
inputs = []
for cond_name in features.keys():
task_idx = getattr(ExtraCondition, cond_name).value
if not isinstance(features[cond_name], list):
inputs.append(features[cond_name] + self.task_embedding[task_idx])
continue
feat_seq = []
for idx, feature_map in enumerate(features[cond_name]):
feature_vec = torch.mean(feature_map, dim=(2, 3))
feature_vec = self.spatial_feat_mapping[idx](feature_vec)
feat_seq.append(feature_vec)
feat_seq = torch.stack(feat_seq, dim=1) # Nx4xC
feat_seq = feat_seq + self.task_embedding[task_idx]
feat_seq = feat_seq + self.positional_embedding
inputs.append(feat_seq)
x = torch.cat(inputs, dim=1) # NxLxC
x = self.ln_pre(x)
x = x.permute(1, 0, 2) # NLD -> LND
x = self.transformer_layes(x)
x = x.permute(1, 0, 2) # LND -> NLD
x = self.ln_post(x)
ret_feat_map = None
ret_feat_seq = None
cur_seq_idx = 0
for cond_name in features.keys():
if not isinstance(features[cond_name], list):
length = features[cond_name].size(1)
transformed_feature = features[cond_name] * (
(x[:, cur_seq_idx : cur_seq_idx + length] @ self.seq_proj) + 1
)
if ret_feat_seq is None:
ret_feat_seq = transformed_feature
else:
ret_feat_seq = torch.cat([ret_feat_seq, transformed_feature], dim=1)
cur_seq_idx += length
continue
length = len(features[cond_name])
transformed_feature_list = []
for idx in range(length):
alpha = self.spatial_ch_projs[idx](x[:, cur_seq_idx + idx])
alpha = alpha.unsqueeze(-1).unsqueeze(-1) + 1
transformed_feature_list.append(features[cond_name][idx] * alpha)
if ret_feat_map is None:
ret_feat_map = transformed_feature_list
else:
ret_feat_map = list(
map(lambda x, y: x + y, ret_feat_map, transformed_feature_list)
)
cur_seq_idx += length
assert cur_seq_idx == x.size(1)
return ret_feat_map, ret_feat_seq
|