Spaces:
Running on Zero
Running on Zero
File size: 9,530 Bytes
0d99394 | 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 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .util import SameBlock2d, DownBlock2d, ResBlock3d
class ModulatedConv3d(nn.Module):
"""
参考 StyleGAN2 的 3D 版本示例,用于替代原先的 Conv3d + InstanceNorm3d + AdaIN。
"""
def __init__(self,
in_channels,
out_channels,
latent_size,
kernel_size=3,
stride=1,
padding=1,
bias=False,
eps=1e-8):
super().__init__()
self.eps = eps
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size if isinstance(kernel_size, tuple) else (kernel_size,)*3
self.stride = stride if isinstance(stride, tuple) else (stride,)*3
self.padding = padding if isinstance(padding, tuple) else (padding,)*3
self.bias = bias
# 卷积权重:维度 [out_channels, in_channels, kD, kH, kW]
# 这里初始化方式可以参考 kaiming_normal 或者 stylegan2 原项目
self.weight = nn.Parameter(torch.randn(
out_channels, in_channels, *self.kernel_size) * 0.01)
# 风格全连接,把 latent 映射到 in_channels
self.style_fc = nn.Linear(latent_size, in_channels, bias=True)
if bias:
self.bias_param = nn.Parameter(torch.zeros(out_channels))
else:
self.bias_param = None
def forward(self, x, latent):
"""
x: [N, inC, D, H, W]
latent: [N, latent_size]
"""
N, _, D, H, W = x.shape
# 1) 计算对 inC 进行的调制系数 scale => [N, inC]
style = self.style_fc(latent) # => [N, inC]
style = style.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1) # => [N, inC, 1, 1, 1]
# 2) 对卷积权重做调制 => w' = w * scale
# 原始 w.shape = [outC, inC, kD, kH, kW]
# 调整后 w_mod.shape = [N, outC, inC, kD, kH, kW]
w = self.weight.unsqueeze(0) # => [1, outC, inC, kD, kH, kW]
w_mod = w * style[:, None, :, :, :, :] # 广播到 [N, outC, inC, kD, kH, kW]
# 3) Demodulation
# 每个样本、每个输出通道的范数,用于对 w_mod 做归一化
# norm.shape = [N, outC, 1, 1, 1, 1]
demod = torch.rsqrt((w_mod**2).sum(dim=(2,3,4,5), keepdim=True) + self.eps)
w_mod = w_mod * demod # => [N, outC, inC, kD, kH, kW]
# 4) 组卷积 (group = N),把 batch 维度展开成 group
# x => [1, N*inC, D, H, W]
# w_mod => [N*outC, inC, kD, kH, kW] (先把 outC 合并到第一维度)
x = x.view(1, N*self.in_channels, D, H, W)
w_mod = w_mod.view(N*self.out_channels, self.in_channels, *self.kernel_size)
out = F.conv3d(
x,
w_mod,
bias=None, # 暂时先不加 bias;如果需要则要同样做拆分
stride=self.stride,
padding=self.padding,
groups=N # 分成 N 组
)
# out.shape = [1, N*outC, D, H, W]
# 还原回 [N, outC, D, H, W]
out = out.view(N, self.out_channels, D, H, W)
# 如果需要 bias,则加上
if self.bias_param is not None:
out = out + self.bias_param.view(1, -1, 1, 1, 1)
return out
class ModulatedConv2d(nn.Module):
"""
类似上面 2D 版本,用于替代原先的 Conv2d + InstanceNorm2d + AdaIN。
"""
def __init__(self,
in_channels,
out_channels,
latent_size,
kernel_size=3,
stride=1,
padding=1,
bias=False,
eps=1e-8):
super().__init__()
self.eps = eps
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size if isinstance(kernel_size, tuple) else (kernel_size,)*2
self.stride = stride if isinstance(stride, tuple) else (stride,)*2
self.padding = padding if isinstance(padding, tuple) else (padding,)*2
self.bias = bias
# 卷积权重
self.weight = nn.Parameter(torch.randn(
out_channels, in_channels, *self.kernel_size) * 0.01)
# 风格全连接
self.style_fc = nn.Linear(latent_size, in_channels, bias=True)
if bias:
self.bias_param = nn.Parameter(torch.zeros(out_channels))
else:
self.bias_param = None
def forward(self, x, latent):
"""
x: [N, inC, H, W]
latent: [N, latent_size]
"""
N, _, H, W = x.shape
# 1) 计算 scale => [N, inC]
style = self.style_fc(latent) # => [N, inC]
style = style.unsqueeze(-1).unsqueeze(-1) # => [N, inC, 1, 1]
# 2) 调制权重
w = self.weight.unsqueeze(0) # => [1, outC, inC, kH, kW]
w_mod = w * style[:, None, :, :, :] # => [N, outC, inC, kH, kW]
# 3) Demodulation
demod = torch.rsqrt((w_mod**2).sum(dim=(2,3,4), keepdim=True) + self.eps)
w_mod = w_mod * demod # => [N, outC, inC, kH, kW]
# 4) 组卷积
x = x.view(1, N*self.in_channels, H, W)
w_mod = w_mod.view(N*self.out_channels, self.in_channels, *self.kernel_size)
out = F.conv2d(
x,
w_mod,
bias=None,
stride=self.stride,
padding=self.padding,
groups=N
)
out = out.view(N, self.out_channels, out.shape[2], out.shape[3])
if self.bias_param is not None:
out = out + self.bias_param.view(1, -1, 1, 1)
return out
class ResnetBlock_StyleGAN2_3D(nn.Module):
def __init__(self, dim=32, latent_size=512, activation=nn.ReLU(True)):
super().__init__()
self.dim = dim
self.act = activation
# 两次 ModulatedConv3d
self.conv1 = ModulatedConv3d(
in_channels=dim,
out_channels=dim,
latent_size=latent_size,
kernel_size=3,
padding=1,
bias=True # 是否加bias,看你需要
)
self.conv2 = ModulatedConv3d(
in_channels=dim,
out_channels=dim,
latent_size=latent_size,
kernel_size=3,
padding=1,
bias=True
)
def forward(self, x, dlatents_in_slice):
"""
x: [N, C, D, H, W]
dlatents_in_slice: [N, latent_size]
"""
y = self.conv1(x, dlatents_in_slice) # => [N, C, D, H, W]
y = self.act(y)
y = self.conv2(y, dlatents_in_slice) # => [N, C, D, H, W]
return x + y # ResNet 残差
class ResnetBlock_StyleGAN2_2D(nn.Module):
def __init__(self, dim=512, latent_size=512, activation=nn.ReLU(True)):
super().__init__()
self.dim = dim
self.act = activation
self.conv1 = ModulatedConv2d(
in_channels=dim,
out_channels=dim,
latent_size=latent_size,
kernel_size=3,
padding=1,
bias=True
)
self.conv2 = ModulatedConv2d(
in_channels=dim,
out_channels=dim,
latent_size=latent_size,
kernel_size=3,
padding=1,
bias=True
)
def forward(self, x, dlatents_in_slice):
y = self.conv1(x, dlatents_in_slice)
y = self.act(y)
y = self.conv2(y, dlatents_in_slice)
return x + y
class transfer_model(nn.Module):
def __init__(self, latent_dim=512, n_blocks=4, padding_type='reflect'):
super(transfer_model, self).__init__()
activation = nn.ReLU(True)
# 3D in
BN_in = []
for i in range(3):
BN_in += [
ResnetBlock_StyleGAN2_3D(dim=32, latent_size=latent_dim, activation=activation)
]
self.BottleNeck_3din = nn.Sequential(*BN_in)
# 2D
BN = []
for i in range(n_blocks):
BN += [
ResnetBlock_StyleGAN2_2D(dim=512, latent_size=latent_dim, activation=activation)
]
self.BottleNeck_2d = nn.Sequential(*BN)
# 3D out
BN_out = []
for i in range(3):
BN_out += [
ResnetBlock_StyleGAN2_3D(dim=32, latent_size=latent_dim, activation=activation)
]
self.BottleNeck_3dout = nn.Sequential(*BN_out)
self.resblocks_3d = torch.nn.Sequential()
for i in range(3):
self.resblocks_3d.add_module('3dr' + str(i), ResBlock3d(32, kernel_size=3, padding=1))
def forward(self, x, dlatents):
# x => [N, 32, D, H, W] 假设是这样
# 1) 3D in
for i in range(len(self.BottleNeck_3din)):
x = self.BottleNeck_3din[i](x, dlatents)
# 2) reshape to 2D => [N, 32*D, H, W]
bs, c, d, h, w = x.shape
x = x.view(bs, c*d, h, w)
# 2D blocks
for i in range(len(self.BottleNeck_2d)):
x = self.BottleNeck_2d[i](x, dlatents)
# reshape back => [N, 32, D, H, W]
x = x.view(bs, c, d, h, w)
# 3) 3D out
for i in range(len(self.BottleNeck_3dout)):
x = self.BottleNeck_3dout[i](x, dlatents)
x = self.resblocks_3d(x)
return x
if __name__ == "__main__":
model = transfer_model()
total_params = sum(p.numel() for p in model.parameters())
print("total parameters:", total_params) |