Create model.py
Browse files
model.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
from einops import rearrange
|
| 4 |
+
|
| 5 |
+
class TimeEmbedding(nn.Module):
|
| 6 |
+
def __init__(self, dim):
|
| 7 |
+
super().__init__()
|
| 8 |
+
self.proj = nn.Sequential(
|
| 9 |
+
nn.Linear(1, dim),
|
| 10 |
+
nn.SiLU(),
|
| 11 |
+
nn.Linear(dim, dim)
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
def forward(self, t):
|
| 15 |
+
return self.proj(t)
|
| 16 |
+
|
| 17 |
+
class Conv3DBlock(nn.Module):
|
| 18 |
+
def __init__(self, in_ch, out_ch, time_dim):
|
| 19 |
+
super().__init__()
|
| 20 |
+
self.time_mlp = nn.Linear(time_dim, out_ch)
|
| 21 |
+
self.conv = nn.Conv3d(in_ch, out_ch, kernel_size=3, padding=1)
|
| 22 |
+
self.norm = nn.BatchNorm3d(out_ch)
|
| 23 |
+
|
| 24 |
+
def forward(self, x, t_emb):
|
| 25 |
+
t_emb = self.time_mlp(t_emb).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
|
| 26 |
+
return F.silu(self.norm(self.conv(x) + t_emb))
|
| 27 |
+
|
| 28 |
+
class UNet3D(nn.Module):
|
| 29 |
+
def __init__(self, in_ch=3, out_ch=3, text_dim=768):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.time_embed = TimeEmbedding(256)
|
| 32 |
+
self.text_proj = nn.Linear(text_dim, 256)
|
| 33 |
+
|
| 34 |
+
# Downsample
|
| 35 |
+
self.down1 = Conv3DBlock(in_ch, 64, 256)
|
| 36 |
+
self.down2 = Conv3DBlock(64, 128, 256)
|
| 37 |
+
self.down3 = Conv3DBlock(128, 256, 256)
|
| 38 |
+
|
| 39 |
+
# Upsample
|
| 40 |
+
self.up1 = Conv3DBlock(256 + 128, 128, 256)
|
| 41 |
+
self.up2 = Conv3DBlock(128 + 64, 64, 256)
|
| 42 |
+
self.up3 = nn.Conv3d(64, out_ch, kernel_size=3, padding=1)
|
| 43 |
+
|
| 44 |
+
def forward(self, x, t, text_emb):
|
| 45 |
+
t_emb = self.time_embed(t)
|
| 46 |
+
text_emb = self.text_proj(text_emb)
|
| 47 |
+
c_emb = t_emb + text_emb
|
| 48 |
+
|
| 49 |
+
# Downsample
|
| 50 |
+
x1 = self.down1(x, c_emb)
|
| 51 |
+
x2 = self.down2(F.max_pool3d(x1, 2), c_emb)
|
| 52 |
+
x3 = self.down3(F.max_pool3d(x2, 2), c_emb)
|
| 53 |
+
|
| 54 |
+
# Upsample
|
| 55 |
+
x = F.interpolate(x3, scale_factor=2)
|
| 56 |
+
x = self.up1(torch.cat([x, x2], dim=1), c_emb)
|
| 57 |
+
x = F.interpolate(x, scale_factor=2)
|
| 58 |
+
x = self.up2(torch.cat([x, x1], dim=1), c_emb)
|
| 59 |
+
x = self.up3(x)
|
| 60 |
+
return x
|