Spaces:
Sleeping
Sleeping
File size: 7,329 Bytes
801501a |
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 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from dotmap import DotMap
from salad.model_components.simple_module import TimePointWiseEncoder, TimestepEmbedder
from salad.model_components.transformer import (
PositionalEncoding,
TimeTransformerDecoder,
TimeTransformerEncoder,
)
class UnCondDiffNetwork(nn.Module):
def __init__(self, input_dim, residual, **kwargs):
"""
Transformer Encoder.
"""
super().__init__()
self.input_dim = input_dim
self.residual = residual
self.__dict__.update(kwargs)
self.hparams = DotMap(self.__dict__)
self._build_model()
def _build_model(self):
self.act = F.leaky_relu
if self.hparams.get("use_timestep_embedder"):
self.time_embedder = TimestepEmbedder(self.hparams.timestep_embedder_dim)
dim_ctx = self.hparams.timestep_embedder_dim
else:
dim_ctx = 3
"""
Encoder part
"""
enc_dim = self.hparams.embedding_dim
self.embedding = nn.Linear(self.hparams.input_dim, enc_dim)
if not self.hparams.get("encoder_type"):
self.encoder = TimeTransformerEncoder(
enc_dim,
dim_ctx=dim_ctx,
num_heads=self.hparams.num_heads
if self.hparams.get("num_heads")
else 4,
use_time=True,
num_layers=self.hparams.enc_num_layers,
last_fc=True,
last_fc_dim_out=self.hparams.input_dim,
)
else:
if self.hparams.encoder_type == "transformer":
self.encoder = TimeTransformerEncoder(
enc_dim,
dim_ctx=dim_ctx,
num_heads=self.hparams.num_heads
if self.hparams.get("num_heads")
else 4,
use_time=True,
num_layers=self.hparams.enc_num_layers,
last_fc=True,
last_fc_dim_out=self.hparams.input_dim,
dropout=self.hparams.get("attn_dropout", 0.0)
)
else:
raise ValueError
def forward(self, x, beta):
"""
Input:
x: [B,G,D] latent
beta: B
Output:
eta: [B,G,D]
"""
B, G = x.shape[:2]
if self.hparams.get("use_timestep_embedder"):
time_emb = self.time_embedder(beta).unsqueeze(1)
else:
beta = beta.view(B, 1, 1)
time_emb = torch.cat(
[beta, torch.sin(beta), torch.cos(beta)], dim=-1
) # [B,1,3]
ctx = time_emb
x_emb = self.embedding(x)
out = self.encoder(x_emb, ctx=ctx)
if self.hparams.residual:
out = out + x
return out
class CondDiffNetwork(nn.Module):
def __init__(self, input_dim, residual, **kwargs):
"""
Transformer Encoder + Decoder.
"""
super().__init__()
self.input_dim = input_dim
self.residual = residual
self.__dict__.update(kwargs)
self.hparams = DotMap(self.__dict__)
self._build_model()
def _build_model(self):
self.act = F.leaky_relu
if self.hparams.get("use_timestep_embedder"):
self.time_embedder = TimestepEmbedder(self.hparams.timestep_embedder_dim)
dim_ctx = self.hparams.timestep_embedder_dim
else:
dim_ctx = 3
"""
Encoder part
"""
enc_dim = self.hparams.context_embedding_dim
self.context_embedding = nn.Linear(self.hparams.context_dim, enc_dim)
if self.hparams.encoder_type == "transformer":
self.encoder = TimeTransformerEncoder(
enc_dim,
3,
num_heads=4,
use_time=self.hparams.encoder_use_time,
num_layers=self.hparams.enc_num_layers
if self.hparams.get("enc_num_layers")
else 3,
last_fc=False,
)
elif self.hparams.encoder_type == "pointwise":
self.encoder = TimePointWiseEncoder(
enc_dim,
dim_ctx=None,
use_time=self.hparams.encoder_use_time,
num_layers=self.hparams.enc_num_layers,
)
else:
raise ValueError
"""
Decoder part
"""
dec_dim = self.hparams.embedding_dim
input_dim = self.hparams.input_dim
self.query_embedding = nn.Linear(self.hparams.input_dim, dec_dim)
if self.hparams.decoder_type == "transformer_decoder":
self.decoder = TimeTransformerDecoder(
dec_dim,
enc_dim,
dim_ctx=dim_ctx,
num_heads=4,
last_fc=True,
last_fc_dim_out=input_dim,
num_layers=self.hparams.dec_num_layers
if self.hparams.get("dec_num_layers")
else 3,
)
elif self.hparams.decoder_type == "transformer_encoder":
self.decoder = TimeTransformerEncoder(
dec_dim,
dim_ctx=enc_dim + dim_ctx,
num_heads=4,
last_fc=True,
last_fc_dim_out=input_dim,
num_layers=self.hparams.dec_num_layers
if self.hparams.get("dec_num_layers")
else 3,
)
else:
raise ValueError
def forward(self, x, beta, context):
"""
Input:
x: [B,G,D] intrinsic
beta: B
context: [B,G,D2] or [B, D2] condition
Output:
eta: [B,G,D]
"""
# print(f"x: {x.shape} context: {context.shape} beta: {beta.shape}")
B, G = x.shape[:2]
if self.hparams.get("use_timestep_embedder"):
time_emb = self.time_embedder(beta).unsqueeze(1)
else:
beta = beta.view(B, 1, 1)
time_emb = torch.cat(
[beta, torch.sin(beta), torch.cos(beta)], dim=-1
) # [B,1,3]
ctx = time_emb
"""
Encoding
"""
cout = self.context_embedding(context)
cout = self.encoder(cout, ctx=ctx if self.hparams.encoder_use_time else None)
if cout.ndim == 2:
cout = cout.unsqueeze(1).expand(-1, G, -1)
"""
Decoding
"""
out = self.query_embedding(x)
if self.hparams.get("use_pos_encoding"):
out = self.pos_encoding(out)
if self.hparams.decoder_type == "transformer_encoder":
try:
ctx = ctx.expand(-1, G, -1)
if cout.ndim == 2:
cout = cout.unsqueeze(1)
cout = cout.expand(-1, G, -1)
ctx = torch.cat([ctx, cout], -1)
except Exception as e:
print(e, G, ctx.shape, cout.shape)
out = self.decoder(out, ctx=ctx)
else:
out = self.decoder(out, cout, ctx=ctx)
# if hasattr(self, "last_fc"):
# out = self.last_fc(out)
if self.hparams.residual:
out = out + x
return out
|