dylanebert commited on
Commit ·
a3fbb44
1
Parent(s): 1144e46
embed mv_unet
Browse filesFiles changed (2)
- mv_unet.pyDeleted-1005
- pipeline.py+1064-25
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005import mathimport numpy as npfrom inspect import isfunctionfrom typing import Optional, Any, List
import torchimport torch.nn as nnimport torch.nn.functional as Ffrom einops import rearrange, repeat
from diffusers.configuration_utils import ConfigMixinfrom diffusers.models.modeling_utils import ModelMixin
# require xformers!import xformersimport xformers.ops
from kiui.cam import orbit_camera
def get_camera( num_frames, elevation=15, azimuth_start=0, azimuth_span=360, blender_coord=True, extra_view=False,): angle_gap = azimuth_span / num_frames cameras = [] for azimuth in np.arange(azimuth_start, azimuth_span + azimuth_start, angle_gap): pose = orbit_camera(-elevation, azimuth, radius=1) # kiui's elevation is negated, [4, 4]
# opengl to blender if blender_coord: pose[2] *= -1 pose[[1, 2]] = pose[[2, 1]]
cameras.append(pose.flatten())
if extra_view: cameras.append(np.zeros_like(cameras[0]))
return torch.from_numpy(np.stack(cameras, axis=0)).float() # [num_frames, 16]
def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False): """ Create sinusoidal timestep embeddings. :param timesteps: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :return: an [N x dim] Tensor of positional embeddings. """ if not repeat_only: half = dim // 2 freqs = torch.exp( -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half ).to(device=timesteps.device) args = timesteps[:, None] * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat( [embedding, torch.zeros_like(embedding[:, :1])], dim=-1 ) else: embedding = repeat(timesteps, "b -> b d", d=dim) # import pdb; pdb.set_trace() return embedding
def zero_module(module): """ Zero out the parameters of a module and return it. """ for p in module.parameters(): p.detach().zero_() return module
def conv_nd(dims, *args, **kwargs): """ Create a 1D, 2D, or 3D convolution module. """ if dims == 1: return nn.Conv1d(*args, **kwargs) elif dims == 2: return nn.Conv2d(*args, **kwargs) elif dims == 3: return nn.Conv3d(*args, **kwargs) raise ValueError(f"unsupported dimensions: {dims}")
def avg_pool_nd(dims, *args, **kwargs): """ Create a 1D, 2D, or 3D average pooling module. """ if dims == 1: return nn.AvgPool1d(*args, **kwargs) elif dims == 2: return nn.AvgPool2d(*args, **kwargs) elif dims == 3: return nn.AvgPool3d(*args, **kwargs) raise ValueError(f"unsupported dimensions: {dims}")
def default(val, d): if val is not None: return val return d() if isfunction(d) else d
class GEGLU(nn.Module): def __init__(self, dim_in, dim_out): super().__init__() self.proj = nn.Linear(dim_in, dim_out * 2)
def forward(self, x): x, gate = self.proj(x).chunk(2, dim=-1) return x * F.gelu(gate)
class FeedForward(nn.Module): def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.0): super().__init__() inner_dim = int(dim * mult) dim_out = default(dim_out, dim) project_in = ( nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU()) if not glu else GEGLU(dim, inner_dim) )
self.net = nn.Sequential( project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out) )
def forward(self, x): return self.net(x)
class MemoryEfficientCrossAttention(nn.Module): # https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223 def __init__( self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0, ip_dim=0, ip_weight=1, ): super().__init__() inner_dim = dim_head * heads context_dim = default(context_dim, query_dim)
self.heads = heads self.dim_head = dim_head
self.ip_dim = ip_dim self.ip_weight = ip_weight
if self.ip_dim > 0: self.to_k_ip = nn.Linear(context_dim, inner_dim, bias=False) self.to_v_ip = nn.Linear(context_dim, inner_dim, bias=False)
self.to_q = nn.Linear(query_dim, inner_dim, bias=False) self.to_k = nn.Linear(context_dim, inner_dim, bias=False) self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
self.to_out = nn.Sequential( nn.Linear(inner_dim, query_dim), nn.Dropout(dropout) ) self.attention_op: Optional[Any] = None
def forward(self, x, context=None): q = self.to_q(x) context = default(context, x)
if self.ip_dim > 0: # context: [B, 77 + 16(ip), 1024] token_len = context.shape[1] context_ip = context[:, -self.ip_dim :, :] k_ip = self.to_k_ip(context_ip) v_ip = self.to_v_ip(context_ip) context = context[:, : (token_len - self.ip_dim), :]
k = self.to_k(context) v = self.to_v(context)
b, _, _ = q.shape q, k, v = map( lambda t: t.unsqueeze(3) .reshape(b, t.shape[1], self.heads, self.dim_head) .permute(0, 2, 1, 3) .reshape(b * self.heads, t.shape[1], self.dim_head) .contiguous(), (q, k, v), )
# actually compute the attention, what we cannot get enough of out = xformers.ops.memory_efficient_attention( q, k, v, attn_bias=None, op=self.attention_op )
if self.ip_dim > 0: k_ip, v_ip = map( lambda t: t.unsqueeze(3) .reshape(b, t.shape[1], self.heads, self.dim_head) .permute(0, 2, 1, 3) .reshape(b * self.heads, t.shape[1], self.dim_head) .contiguous(), (k_ip, v_ip), ) # actually compute the attention, what we cannot get enough of out_ip = xformers.ops.memory_efficient_attention( q, k_ip, v_ip, attn_bias=None, op=self.attention_op ) out = out + self.ip_weight * out_ip
out = ( out.unsqueeze(0) .reshape(b, self.heads, out.shape[1], self.dim_head) .permute(0, 2, 1, 3) .reshape(b, out.shape[1], self.heads * self.dim_head) ) return self.to_out(out)
class BasicTransformerBlock3D(nn.Module): def __init__( self, dim, n_heads, d_head, context_dim, dropout=0.0, gated_ff=True, ip_dim=0, ip_weight=1, ): super().__init__()
self.attn1 = MemoryEfficientCrossAttention( query_dim=dim, context_dim=None, # self-attention heads=n_heads, dim_head=d_head, dropout=dropout, ) self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff) self.attn2 = MemoryEfficientCrossAttention( query_dim=dim, context_dim=context_dim, heads=n_heads, dim_head=d_head, dropout=dropout, # ip only applies to cross-attention ip_dim=ip_dim, ip_weight=ip_weight, ) self.norm1 = nn.LayerNorm(dim) self.norm2 = nn.LayerNorm(dim) self.norm3 = nn.LayerNorm(dim)
def forward(self, x, context=None, num_frames=1): x = rearrange(x, "(b f) l c -> b (f l) c", f=num_frames).contiguous() x = self.attn1(self.norm1(x), context=None) + x x = rearrange(x, "b (f l) c -> (b f) l c", f=num_frames).contiguous() x = self.attn2(self.norm2(x), context=context) + x x = self.ff(self.norm3(x)) + x return x
class SpatialTransformer3D(nn.Module):
def __init__( self, in_channels, n_heads, d_head, context_dim, # cross attention input dim depth=1, dropout=0.0, ip_dim=0, ip_weight=1, ): super().__init__()
if not isinstance(context_dim, list): context_dim = [context_dim]
self.in_channels = in_channels
inner_dim = n_heads * d_head self.norm = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True) self.proj_in = nn.Linear(in_channels, inner_dim)
self.transformer_blocks = nn.ModuleList( [ BasicTransformerBlock3D( inner_dim, n_heads, d_head, context_dim=context_dim[d], dropout=dropout, ip_dim=ip_dim, ip_weight=ip_weight, ) for d in range(depth) ] ) self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))
def forward(self, x, context=None, num_frames=1): # note: if no context is given, cross-attention defaults to self-attention if not isinstance(context, list): context = [context] b, c, h, w = x.shape x_in = x x = self.norm(x) x = rearrange(x, "b c h w -> b (h w) c").contiguous() x = self.proj_in(x) for i, block in enumerate(self.transformer_blocks): x = block(x, context=context[i], num_frames=num_frames) x = self.proj_out(x) x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w).contiguous() return x + x_in
class PerceiverAttention(nn.Module): def __init__(self, *, dim, dim_head=64, heads=8): super().__init__() self.scale = dim_head ** -0.5 self.dim_head = dim_head self.heads = heads inner_dim = dim_head * heads
self.norm1 = nn.LayerNorm(dim) self.norm2 = nn.LayerNorm(dim)
self.to_q = nn.Linear(dim, inner_dim, bias=False) self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False) self.to_out = nn.Linear(inner_dim, dim, bias=False)
def forward(self, x, latents): """ Args: x (torch.Tensor): image features shape (b, n1, D) latent (torch.Tensor): latent features shape (b, n2, D) """ x = self.norm1(x) latents = self.norm2(latents)
b, l, _ = latents.shape
q = self.to_q(latents) kv_input = torch.cat((x, latents), dim=-2) k, v = self.to_kv(kv_input).chunk(2, dim=-1)
q, k, v = map( lambda t: t.reshape(b, t.shape[1], self.heads, -1) .transpose(1, 2) .reshape(b, self.heads, t.shape[1], -1) .contiguous(), (q, k, v), )
# attention scale = 1 / math.sqrt(math.sqrt(self.dim_head)) weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype) out = weight @ v
out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
return self.to_out(out)
class Resampler(nn.Module): def __init__( self, dim=1024, depth=8, dim_head=64, heads=16, num_queries=8, embedding_dim=768, output_dim=1024, ff_mult=4, ): super().__init__() self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim ** 0.5) self.proj_in = nn.Linear(embedding_dim, dim) self.proj_out = nn.Linear(dim, output_dim) self.norm_out = nn.LayerNorm(output_dim)
self.layers = nn.ModuleList([]) for _ in range(depth): self.layers.append( nn.ModuleList( [ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads), nn.Sequential( nn.LayerNorm(dim), nn.Linear(dim, dim * ff_mult, bias=False), nn.GELU(), nn.Linear(dim * ff_mult, dim, bias=False), ) ] ) )
def forward(self, x): latents = self.latents.repeat(x.size(0), 1, 1) x = self.proj_in(x) for attn, ff in self.layers: latents = attn(x, latents) + latents latents = ff(latents) + latents
latents = self.proj_out(latents) return self.norm_out(latents)
class CondSequential(nn.Sequential): """ A sequential module that passes timestep embeddings to the children that support it as an extra input. """
def forward(self, x, emb, context=None, num_frames=1): for layer in self: if isinstance(layer, ResBlock): x = layer(x, emb) elif isinstance(layer, SpatialTransformer3D): x = layer(x, context, num_frames=num_frames) else: x = layer(x) return x
class Upsample(nn.Module): """ An upsampling 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 upsampling 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 if use_conv: self.conv = conv_nd( dims, self.channels, self.out_channels, 3, padding=padding )
def forward(self, x): assert x.shape[1] == self.channels if self.dims == 3: x = F.interpolate( x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest" ) else: x = F.interpolate(x, scale_factor=2, mode="nearest") if self.use_conv: x = self.conv(x) return x
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 ResBlock(nn.Module): """ A residual block that can optionally change the number of channels. :param channels: the number of input channels. :param emb_channels: the number of timestep embedding channels. :param dropout: the rate of dropout. :param out_channels: if specified, the number of out channels. :param use_conv: if True and out_channels is specified, use a spatial convolution instead of a smaller 1x1 convolution to change the channels in the skip connection. :param dims: determines if the signal is 1D, 2D, or 3D. :param up: if True, use this block for upsampling. :param down: if True, use this block for downsampling. """
def __init__( self, channels, emb_channels, dropout, out_channels=None, use_conv=False, use_scale_shift_norm=False, dims=2, up=False, down=False, ): super().__init__() self.channels = channels self.emb_channels = emb_channels self.dropout = dropout self.out_channels = out_channels or channels self.use_conv = use_conv self.use_scale_shift_norm = use_scale_shift_norm
self.in_layers = nn.Sequential( nn.GroupNorm(32, channels), nn.SiLU(), conv_nd(dims, channels, self.out_channels, 3, padding=1), )
self.updown = up or down
if up: self.h_upd = Upsample(channels, False, dims) self.x_upd = Upsample(channels, False, dims) elif down: self.h_upd = Downsample(channels, False, dims) self.x_upd = Downsample(channels, False, dims) else: self.h_upd = self.x_upd = nn.Identity()
self.emb_layers = nn.Sequential( nn.SiLU(), nn.Linear( emb_channels, 2 * self.out_channels if use_scale_shift_norm else self.out_channels, ), ) self.out_layers = nn.Sequential( nn.GroupNorm(32, self.out_channels), nn.SiLU(), nn.Dropout(p=dropout), zero_module( conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1) ), )
if self.out_channels == channels: self.skip_connection = nn.Identity() elif use_conv: self.skip_connection = conv_nd( dims, channels, self.out_channels, 3, padding=1 ) else: self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
def forward(self, x, emb): if self.updown: in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1] h = in_rest(x) h = self.h_upd(h) x = self.x_upd(x) h = in_conv(h) else: h = self.in_layers(x) emb_out = self.emb_layers(emb).type(h.dtype) while len(emb_out.shape) < len(h.shape): emb_out = emb_out[..., None] if self.use_scale_shift_norm: out_norm, out_rest = self.out_layers[0], self.out_layers[1:] scale, shift = torch.chunk(emb_out, 2, dim=1) h = out_norm(h) * (1 + scale) + shift h = out_rest(h) else: h = h + emb_out h = self.out_layers(h) return self.skip_connection(x) + h
class MultiViewUNetModel(ModelMixin, ConfigMixin): """ The full multi-view UNet model with attention, timestep embedding and camera embedding. :param in_channels: channels in the input Tensor. :param model_channels: base channel count for the model. :param out_channels: channels in the output Tensor. :param num_res_blocks: number of residual blocks per downsample. :param attention_resolutions: a collection of downsample rates at which attention will take place. May be a set, list, or tuple. For example, if this contains 4, then at 4x downsampling, attention will be used. :param dropout: the dropout probability. :param channel_mult: channel multiplier for each level of the UNet. :param conv_resample: if True, use learned convolutions for upsampling and downsampling. :param dims: determines if the signal is 1D, 2D, or 3D. :param num_classes: if specified (as an int), then this model will be class-conditional with `num_classes` classes. :param num_heads: the number of attention heads in each attention layer. :param num_heads_channels: if specified, ignore num_heads and instead use a fixed channel width per attention head. :param num_heads_upsample: works with num_heads to set a different number of heads for upsampling. Deprecated. :param use_scale_shift_norm: use a FiLM-like conditioning mechanism. :param resblock_updown: use residual blocks for up/downsampling. :param use_new_attention_order: use a different attention pattern for potentially increased efficiency. :param camera_dim: dimensionality of camera input. """
def __init__( self, image_size, in_channels, model_channels, out_channels, num_res_blocks, attention_resolutions, dropout=0, channel_mult=(1, 2, 4, 8), conv_resample=True, dims=2, num_classes=None, num_heads=-1, num_head_channels=-1, num_heads_upsample=-1, use_scale_shift_norm=False, resblock_updown=False, transformer_depth=1, context_dim=None, n_embed=None, num_attention_blocks=None, adm_in_channels=None, camera_dim=None, ip_dim=0, # imagedream uses ip_dim > 0 ip_weight=1.0, **kwargs, ): super().__init__() assert context_dim is not None if num_heads_upsample == -1: num_heads_upsample = num_heads
if num_heads == -1: assert ( num_head_channels != -1 ), "Either num_heads or num_head_channels has to be set"
if num_head_channels == -1: assert ( num_heads != -1 ), "Either num_heads or num_head_channels has to be set"
self.image_size = image_size self.in_channels = in_channels self.model_channels = model_channels self.out_channels = out_channels if isinstance(num_res_blocks, int): self.num_res_blocks = len(channel_mult) * [num_res_blocks] else: if len(num_res_blocks) != len(channel_mult): raise ValueError( "provide num_res_blocks either as an int (globally constant) or " "as a list/tuple (per-level) with the same length as channel_mult" ) self.num_res_blocks = num_res_blocks if num_attention_blocks is not None: assert len(num_attention_blocks) == len(self.num_res_blocks) assert all( map( lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks)), ) ) print( f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. " f"This option has LESS priority than attention_resolutions {attention_resolutions}, " f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, " f"attention will still not be set." )
self.attention_resolutions = attention_resolutions self.dropout = dropout self.channel_mult = channel_mult self.conv_resample = conv_resample self.num_classes = num_classes self.num_heads = num_heads self.num_head_channels = num_head_channels self.num_heads_upsample = num_heads_upsample self.predict_codebook_ids = n_embed is not None
self.ip_dim = ip_dim self.ip_weight = ip_weight
if self.ip_dim > 0: self.image_embed = Resampler( dim=context_dim, depth=4, dim_head=64, heads=12, num_queries=ip_dim, # num token embedding_dim=1280, output_dim=context_dim, ff_mult=4, )
time_embed_dim = model_channels * 4 self.time_embed = nn.Sequential( nn.Linear(model_channels, time_embed_dim), nn.SiLU(), nn.Linear(time_embed_dim, time_embed_dim), )
if camera_dim is not None: time_embed_dim = model_channels * 4 self.camera_embed = nn.Sequential( nn.Linear(camera_dim, time_embed_dim), nn.SiLU(), nn.Linear(time_embed_dim, time_embed_dim), )
if self.num_classes is not None: if isinstance(self.num_classes, int): self.label_emb = nn.Embedding(self.num_classes, time_embed_dim) elif self.num_classes == "continuous": # print("setting up linear c_adm embedding layer") self.label_emb = nn.Linear(1, time_embed_dim) elif self.num_classes == "sequential": assert adm_in_channels is not None self.label_emb = nn.Sequential( nn.Sequential( nn.Linear(adm_in_channels, time_embed_dim), nn.SiLU(), nn.Linear(time_embed_dim, time_embed_dim), ) ) else: raise ValueError()
self.input_blocks = nn.ModuleList( [ CondSequential( conv_nd(dims, in_channels, model_channels, 3, padding=1) ) ] ) self._feature_size = model_channels input_block_chans = [model_channels] ch = model_channels ds = 1 for level, mult in enumerate(channel_mult): for nr in range(self.num_res_blocks[level]): layers: List[Any] = [ ResBlock( ch, time_embed_dim, dropout, out_channels=mult * model_channels, dims=dims, use_scale_shift_norm=use_scale_shift_norm, ) ] ch = mult * model_channels if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels
if num_attention_blocks is None or nr < num_attention_blocks[level]: layers.append( SpatialTransformer3D( ch, num_heads, dim_head, context_dim=context_dim, depth=transformer_depth, ip_dim=self.ip_dim, ip_weight=self.ip_weight, ) ) self.input_blocks.append(CondSequential(*layers)) self._feature_size += ch input_block_chans.append(ch) if level != len(channel_mult) - 1: out_ch = ch self.input_blocks.append( CondSequential( ResBlock( ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_scale_shift_norm=use_scale_shift_norm, down=True, ) if resblock_updown else Downsample( ch, conv_resample, dims=dims, out_channels=out_ch ) ) ) ch = out_ch input_block_chans.append(ch) ds *= 2 self._feature_size += ch
if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels self.middle_block = CondSequential( ResBlock( ch, time_embed_dim, dropout, dims=dims, use_scale_shift_norm=use_scale_shift_norm, ), SpatialTransformer3D( ch, num_heads, dim_head, context_dim=context_dim, depth=transformer_depth, ip_dim=self.ip_dim, ip_weight=self.ip_weight, ), ResBlock( ch, time_embed_dim, dropout, dims=dims, use_scale_shift_norm=use_scale_shift_norm, ), ) self._feature_size += ch
self.output_blocks = nn.ModuleList([]) for level, mult in list(enumerate(channel_mult))[::-1]: for i in range(self.num_res_blocks[level] + 1): ich = input_block_chans.pop() layers = [ ResBlock( ch + ich, time_embed_dim, dropout, out_channels=model_channels * mult, dims=dims, use_scale_shift_norm=use_scale_shift_norm, ) ] ch = model_channels * mult if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels
if num_attention_blocks is None or i < num_attention_blocks[level]: layers.append( SpatialTransformer3D( ch, num_heads, dim_head, context_dim=context_dim, depth=transformer_depth, ip_dim=self.ip_dim, ip_weight=self.ip_weight, ) ) if level and i == self.num_res_blocks[level]: out_ch = ch layers.append( ResBlock( ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_scale_shift_norm=use_scale_shift_norm, up=True, ) if resblock_updown else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) ) ds //= 2 self.output_blocks.append(CondSequential(*layers)) self._feature_size += ch
self.out = nn.Sequential( nn.GroupNorm(32, ch), nn.SiLU(), zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)), ) if self.predict_codebook_ids: self.id_predictor = nn.Sequential( nn.GroupNorm(32, ch), conv_nd(dims, model_channels, n_embed, 1), # nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits )
def forward( self, x, timesteps=None, context=None, y=None, camera=None, num_frames=1, ip=None, ip_img=None, **kwargs, ): """ Apply the model to an input batch. :param x: an [(N x F) x C x ...] Tensor of inputs. F is the number of frames (views). :param timesteps: a 1-D batch of timesteps. :param context: conditioning plugged in via crossattn :param y: an [N] Tensor of labels, if class-conditional. :param num_frames: a integer indicating number of frames for tensor reshaping. :return: an [(N x F) x C x ...] Tensor of outputs. F is the number of frames (views). """ assert ( x.shape[0] % num_frames == 0 ), "input batch size must be dividable by num_frames!" assert (y is not None) == ( self.num_classes is not None ), "must specify y if and only if the model is class-conditional"
hs = []
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
emb = self.time_embed(t_emb)
if self.num_classes is not None: assert y is not None assert y.shape[0] == x.shape[0] emb = emb + self.label_emb(y)
# Add camera embeddings if camera is not None: emb = emb + self.camera_embed(camera) # imagedream variant if self.ip_dim > 0: x[(num_frames - 1) :: num_frames, :, :, :] = ip_img # place at [4, 9] ip_emb = self.image_embed(ip) context = torch.cat((context, ip_emb), 1)
h = x for module in self.input_blocks: h = module(h, emb, context, num_frames=num_frames) hs.append(h) h = self.middle_block(h, emb, context, num_frames=num_frames) for module in self.output_blocks: h = torch.cat([h, hs.pop()], dim=1) h = module(h, emb, context, num_frames=num_frames) h = h.type(x.dtype) if self.predict_codebook_ids: return self.id_predictor(h) else: return self.out(h)1 unmodified line234567895 unmodified lines15161718192021382 unmodified lines40440540640740840941041141241341441541641741841942042142242342442542642742842912 unmodified lines44244344444544644744816 unmodified lines46546646746846947047147247317 unmodified lines4914924934944954964976 unmodified lines50450550650750850951051151251351451551651751851952052152252323 unmodified lines5475485495505515525531 unmodified lineimport torch.nn.functional as Fimport inspectimport numpy as npfrom typing import Callable, List, Optional, Unionfrom transformers import CLIPTextModel, CLIPTokenizer, CLIPVisionModel, CLIPImageProcessorfrom diffusers import AutoencoderKL, DiffusionPipelinefrom diffusers.utils import (deprecate,5 unmodified linesfrom diffusers.schedulers import DDIMSchedulerfrom diffusers.utils.torch_utils import randn_tensorfrom mv_unet import MultiViewUNetModel, get_cameralogger = logging.get_logger(__name__) # pylint: disable=invalid-name382 unmodified linesif image.dtype == np.float32:image = (image * 255).astype(np.uint8)image = self.feature_extractor(image, return_tensors="pt").pixel_valuesimage = image.to(device=device, dtype=dtype)image_embeds = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)return torch.zeros_like(image_embeds), image_embedsdef encode_image_latents(self, image, device, num_images_per_prompt):dtype = next(self.image_encoder.parameters()).dtypeimage = torch.from_numpy(image).unsqueeze(0).permute(0, 3, 1, 2).to(device=device) # [1, 3, H, W]image = 2 * image - 1image = F.interpolate(image, (256, 256), mode='bilinear', align_corners=False)image = image.to(dtype=dtype)posterior = self.vae.encode(image).latent_distlatents = posterior.sample() * self.vae.config.scaling_factor # [B, C, H, W]latents = latents.repeat_interleave(num_images_per_prompt, dim=0)return torch.zeros_like(latents), latents12 unmodified linesnum_images_per_prompt: int = 1,eta: float = 0.0,generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,output_type: Optional[str] = "numpy", # pil, numpy, latentscallback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,callback_steps: int = 1,num_frames: int = 4,16 unmodified linesif image is not None:assert isinstance(image, np.ndarray) and image.dtype == np.float32self.image_encoder = self.image_encoder.to(device=device)image_embeds_neg, image_embeds_pos = self.encode_image(image, device, num_images_per_prompt)image_latents_neg, image_latents_pos = self.encode_image_latents(image, device, num_images_per_prompt)_prompt_embeds = self._encode_prompt(prompt=prompt,device=device,17 unmodified lines)# Get cameracamera = get_camera(num_frames, elevation=elevation, extra_view=(image is not None)).to(dtype=latents.dtype, device=device)camera = camera.repeat_interleave(num_images_per_prompt, dim=0)# Prepare extra step kwargs.6 unmodified lines# expand the latents if we are doing classifier free guidancemultiplier = 2 if do_classifier_free_guidance else 1latent_model_input = torch.cat([latents] * multiplier)latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)unet_inputs = {'x': latent_model_input,'timesteps': torch.tensor([t] * actual_num_frames * multiplier, dtype=latent_model_input.dtype, device=device),'context': torch.cat([prompt_embeds_neg] * actual_num_frames + [prompt_embeds_pos] * actual_num_frames),'num_frames': actual_num_frames,'camera': torch.cat([camera] * multiplier),}if image is not None:unet_inputs['ip'] = torch.cat([image_embeds_neg] * actual_num_frames + [image_embeds_pos] * actual_num_frames)unet_inputs['ip_img'] = torch.cat([image_latents_neg] + [image_latents_pos]) # no repeat# predict the noise residualnoise_pred = self.unet.forward(**unet_inputs)23 unmodified lineselif output_type == "pil":image = self.decode_latents(latents)image = self.numpy_to_pil(image)else: # numpyimage = self.decode_latents(latents)# Offload last model to CPU1 unmodified line2345678910111213145 unmodified lines20212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036382 unmodified lines14191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144812 unmodified lines146114621463146414651466146716 unmodified lines148414851486148714881489149014911492149314941495149617 unmodified lines1514151515161517151815191520152115226 unmodified lines152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156223 unmodified lines15861587158815891590159115921 unmodified lineimport torch.nn.functional as Fimport inspectimport numpy as npfrom typing import Callable, List, Optional, Union, Anyfrom transformers import (CLIPTextModel,CLIPTokenizer,CLIPVisionModel,CLIPImageProcessor,)from diffusers import AutoencoderKL, DiffusionPipelinefrom diffusers.utils import (deprecate,5 unmodified linesfrom diffusers.schedulers import DDIMSchedulerfrom diffusers.utils.torch_utils import randn_tensorimport mathfrom inspect import isfunctionimport torch.nn as nnfrom einops import rearrange, repeatfrom diffusers.configuration_utils import ConfigMixinfrom diffusers.models.modeling_utils import ModelMixin# require xformers!import xformersimport xformers.opsfrom kiui.cam import orbit_cameradef get_camera(num_frames,elevation=15,azimuth_start=0,azimuth_span=360,blender_coord=True,extra_view=False,):angle_gap = azimuth_span / num_framescameras = []for azimuth in np.arange(azimuth_start, azimuth_span + azimuth_start, angle_gap):pose = orbit_camera(-elevation, azimuth, radius=1) # kiui's elevation is negated, [4, 4]# opengl to blenderif blender_coord:pose[2] *= -1pose[[1, 2]] = pose[[2, 1]]cameras.append(pose.flatten())if extra_view:cameras.append(np.zeros_like(cameras[0]))return torch.from_numpy(np.stack(cameras, axis=0)).float() # [num_frames, 16]def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):"""Create sinusoidal timestep embeddings.:param timesteps: a 1-D Tensor of N indices, one per batch element.These may be fractional.:param dim: the dimension of the output.:param max_period: controls the minimum frequency of the embeddings.:return: an [N x dim] Tensor of positional embeddings."""if not repeat_only:half = dim // 2freqs = torch.exp(-math.log(max_period)* torch.arange(start=0, end=half, dtype=torch.float32)/ half).to(device=timesteps.device)args = timesteps[:, None] * freqs[None]embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)if dim % 2:embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)else:embedding = repeat(timesteps, "b -> b d", d=dim)# import pdb; pdb.set_trace()return embeddingdef zero_module(module):"""Zero out the parameters of a module and return it."""for p in module.parameters():p.detach().zero_()return moduledef conv_nd(dims, *args, **kwargs):"""Create a 1D, 2D, or 3D convolution module."""if dims == 1:return nn.Conv1d(*args, **kwargs)elif dims == 2:return nn.Conv2d(*args, **kwargs)elif dims == 3:return nn.Conv3d(*args, **kwargs)raise ValueError(f"unsupported dimensions: {dims}")def avg_pool_nd(dims, *args, **kwargs):"""Create a 1D, 2D, or 3D average pooling module."""if dims == 1:return nn.AvgPool1d(*args, **kwargs)elif dims == 2:return nn.AvgPool2d(*args, **kwargs)elif dims == 3:return nn.AvgPool3d(*args, **kwargs)raise ValueError(f"unsupported dimensions: {dims}")def default(val, d):if val is not None:return valreturn d() if isfunction(d) else dclass GEGLU(nn.Module):def __init__(self, dim_in, dim_out):super().__init__()self.proj = nn.Linear(dim_in, dim_out * 2)def forward(self, x):x, gate = self.proj(x).chunk(2, dim=-1)return x * F.gelu(gate)class FeedForward(nn.Module):def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.0):super().__init__()inner_dim = int(dim * mult)dim_out = default(dim_out, dim)project_in = (nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU())if not gluelse GEGLU(dim, inner_dim))self.net = nn.Sequential(project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out))def forward(self, x):return self.net(x)class MemoryEfficientCrossAttention(nn.Module):# https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223def __init__(self,query_dim,context_dim=None,heads=8,dim_head=64,dropout=0.0,ip_dim=0,ip_weight=1,):super().__init__()inner_dim = dim_head * headscontext_dim = default(context_dim, query_dim)self.heads = headsself.dim_head = dim_headself.ip_dim = ip_dimself.ip_weight = ip_weightif self.ip_dim > 0:self.to_k_ip = nn.Linear(context_dim, inner_dim, bias=False)self.to_v_ip = nn.Linear(context_dim, inner_dim, bias=False)self.to_q = nn.Linear(query_dim, inner_dim, bias=False)self.to_k = nn.Linear(context_dim, inner_dim, bias=False)self.to_v = nn.Linear(context_dim, inner_dim, bias=False)self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))self.attention_op: Optional[Any] = Nonedef forward(self, x, context=None):q = self.to_q(x)context = default(context, x)if self.ip_dim > 0:# context: [B, 77 + 16(ip), 1024]token_len = context.shape[1]context_ip = context[:, -self.ip_dim :, :]k_ip = self.to_k_ip(context_ip)v_ip = self.to_v_ip(context_ip)context = context[:, : (token_len - self.ip_dim), :]k = self.to_k(context)v = self.to_v(context)b, _, _ = q.shapeq, k, v = map(lambda t: t.unsqueeze(3).reshape(b, t.shape[1], self.heads, self.dim_head).permute(0, 2, 1, 3).reshape(b * self.heads, t.shape[1], self.dim_head).contiguous(),(q, k, v),)# actually compute the attention, what we cannot get enough ofout = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)if self.ip_dim > 0:k_ip, v_ip = map(lambda t: t.unsqueeze(3).reshape(b, t.shape[1], self.heads, self.dim_head).permute(0, 2, 1, 3).reshape(b * self.heads, t.shape[1], self.dim_head).contiguous(),(k_ip, v_ip),)# actually compute the attention, what we cannot get enough ofout_ip = xformers.ops.memory_efficient_attention(q, k_ip, v_ip, attn_bias=None, op=self.attention_op)out = out + self.ip_weight * out_ipout = (out.unsqueeze(0).reshape(b, self.heads, out.shape[1], self.dim_head).permute(0, 2, 1, 3).reshape(b, out.shape[1], self.heads * self.dim_head))return self.to_out(out)class BasicTransformerBlock3D(nn.Module):def __init__(self,dim,n_heads,d_head,context_dim,dropout=0.0,gated_ff=True,ip_dim=0,ip_weight=1,):super().__init__()self.attn1 = MemoryEfficientCrossAttention(query_dim=dim,context_dim=None, # self-attentionheads=n_heads,dim_head=d_head,dropout=dropout,)self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)self.attn2 = MemoryEfficientCrossAttention(query_dim=dim,context_dim=context_dim,heads=n_heads,dim_head=d_head,dropout=dropout,# ip only applies to cross-attentionip_dim=ip_dim,ip_weight=ip_weight,)self.norm1 = nn.LayerNorm(dim)self.norm2 = nn.LayerNorm(dim)self.norm3 = nn.LayerNorm(dim)def forward(self, x, context=None, num_frames=1):x = rearrange(x, "(b f) l c -> b (f l) c", f=num_frames).contiguous()x = self.attn1(self.norm1(x), context=None) + xx = rearrange(x, "b (f l) c -> (b f) l c", f=num_frames).contiguous()x = self.attn2(self.norm2(x), context=context) + xx = self.ff(self.norm3(x)) + xreturn xclass SpatialTransformer3D(nn.Module):def __init__(self,in_channels,n_heads,d_head,context_dim, # cross attention input dimdepth=1,dropout=0.0,ip_dim=0,ip_weight=1,):super().__init__()if not isinstance(context_dim, list):context_dim = [context_dim]self.in_channels = in_channelsinner_dim = n_heads * d_headself.norm = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)self.proj_in = nn.Linear(in_channels, inner_dim)self.transformer_blocks = nn.ModuleList([BasicTransformerBlock3D(inner_dim,n_heads,d_head,context_dim=context_dim[d],dropout=dropout,ip_dim=ip_dim,ip_weight=ip_weight,)for d in range(depth)])self.proj_out = zero_module(nn.Linear(in_channels, inner_dim))def forward(self, x, context=None, num_frames=1):# note: if no context is given, cross-attention defaults to self-attentionif not isinstance(context, list):context = [context]b, c, h, w = x.shapex_in = xx = self.norm(x)x = rearrange(x, "b c h w -> b (h w) c").contiguous()x = self.proj_in(x)for i, block in enumerate(self.transformer_blocks):x = block(x, context=context[i], num_frames=num_frames)x = self.proj_out(x)x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w).contiguous()return x + x_inclass PerceiverAttention(nn.Module):def __init__(self, *, dim, dim_head=64, heads=8):super().__init__()self.scale = dim_head**-0.5self.dim_head = dim_headself.heads = headsinner_dim = dim_head * headsself.norm1 = nn.LayerNorm(dim)self.norm2 = nn.LayerNorm(dim)self.to_q = nn.Linear(dim, inner_dim, bias=False)self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)self.to_out = nn.Linear(inner_dim, dim, bias=False)def forward(self, x, latents):"""Args:x (torch.Tensor): image featuresshape (b, n1, D)latent (torch.Tensor): latent featuresshape (b, n2, D)"""x = self.norm1(x)latents = self.norm2(latents)b, h, _ = latents.shapeq = self.to_q(latents)kv_input = torch.cat((x, latents), dim=-2)k, v = self.to_kv(kv_input).chunk(2, dim=-1)q, k, v = map(lambda t: t.reshape(b, t.shape[1], self.heads, -1).transpose(1, 2).reshape(b, self.heads, t.shape[1], -1).contiguous(),(q, k, v),)# attentionscale = 1 / math.sqrt(math.sqrt(self.dim_head))weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwardsweight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)out = weight @ vout = out.permute(0, 2, 1, 3).reshape(b, h, -1)return self.to_out(out)class Resampler(nn.Module):def __init__(self,dim=1024,depth=8,dim_head=64,heads=16,num_queries=8,embedding_dim=768,output_dim=1024,ff_mult=4,):super().__init__()self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)self.proj_in = nn.Linear(embedding_dim, dim)self.proj_out = nn.Linear(dim, output_dim)self.norm_out = nn.LayerNorm(output_dim)self.layers = nn.ModuleList([])for _ in range(depth):self.layers.append(nn.ModuleList([PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),nn.Sequential(nn.LayerNorm(dim),nn.Linear(dim, dim * ff_mult, bias=False),nn.GELU(),nn.Linear(dim * ff_mult, dim, bias=False),),]))def forward(self, x):latents = self.latents.repeat(x.size(0), 1, 1)x = self.proj_in(x)for attn, ff in self.layers:latents = attn(x, latents) + latentslatents = ff(latents) + latentslatents = self.proj_out(latents)return self.norm_out(latents)class CondSequential(nn.Sequential):"""A sequential module that passes timestep embeddings to the children thatsupport it as an extra input."""def forward(self, x, emb, context=None, num_frames=1):for layer in self:if isinstance(layer, ResBlock):x = layer(x, emb)elif isinstance(layer, SpatialTransformer3D):x = layer(x, context, num_frames=num_frames)else:x = layer(x)return xclass Upsample(nn.Module):"""An upsampling 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, thenupsampling occurs in the inner-two dimensions."""def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):super().__init__()self.channels = channelsself.out_channels = out_channels or channelsself.use_conv = use_convself.dims = dimsif use_conv:self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding)def forward(self, x):assert x.shape[1] == self.channelsif self.dims == 3:x = F.interpolate(x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest")else:x = F.interpolate(x, scale_factor=2, mode="nearest")if self.use_conv:x = self.conv(x)return xclass 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, thendownsampling occurs in the inner-two dimensions."""def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):super().__init__()self.channels = channelsself.out_channels = out_channels or channelsself.use_conv = use_convself.dims = dimsstride = 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_channelsself.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)def forward(self, x):assert x.shape[1] == self.channelsreturn self.op(x)class ResBlock(nn.Module):"""A residual block that can optionally change the number of channels.:param channels: the number of input channels.:param emb_channels: the number of timestep embedding channels.:param dropout: the rate of dropout.:param out_channels: if specified, the number of out channels.:param use_conv: if True and out_channels is specified, use a spatialconvolution instead of a smaller 1x1 convolution to change thechannels in the skip connection.:param dims: determines if the signal is 1D, 2D, or 3D.:param up: if True, use this block for upsampling.:param down: if True, use this block for downsampling."""def __init__(self,channels,emb_channels,dropout,out_channels=None,use_conv=False,use_scale_shift_norm=False,dims=2,up=False,down=False,):super().__init__()self.channels = channelsself.emb_channels = emb_channelsself.dropout = dropoutself.out_channels = out_channels or channelsself.use_conv = use_convself.use_scale_shift_norm = use_scale_shift_normself.in_layers = nn.Sequential(nn.GroupNorm(32, channels),nn.SiLU(),conv_nd(dims, channels, self.out_channels, 3, padding=1),)self.updown = up or downif up:self.h_upd = Upsample(channels, False, dims)self.x_upd = Upsample(channels, False, dims)elif down:self.h_upd = Downsample(channels, False, dims)self.x_upd = Downsample(channels, False, dims)else:self.h_upd = self.x_upd = nn.Identity()self.emb_layers = nn.Sequential(nn.SiLU(),nn.Linear(emb_channels,2 * self.out_channels if use_scale_shift_norm else self.out_channels,),)self.out_layers = nn.Sequential(nn.GroupNorm(32, self.out_channels),nn.SiLU(),nn.Dropout(p=dropout),zero_module(conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)),)if self.out_channels == channels:self.skip_connection = nn.Identity()elif use_conv:self.skip_connection = conv_nd(dims, channels, self.out_channels, 3, padding=1)else:self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)def forward(self, x, emb):if self.updown:in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]h = in_rest(x)h = self.h_upd(h)x = self.x_upd(x)h = in_conv(h)else:h = self.in_layers(x)emb_out = self.emb_layers(emb).type(h.dtype)while len(emb_out.shape) < len(h.shape):emb_out = emb_out[..., None]if self.use_scale_shift_norm:out_norm, out_rest = self.out_layers[0], self.out_layers[1:]scale, shift = torch.chunk(emb_out, 2, dim=1)h = out_norm(h) * (1 + scale) + shifth = out_rest(h)else:h = h + emb_outh = self.out_layers(h)return self.skip_connection(x) + hclass MultiViewUNetModel(ModelMixin, ConfigMixin):"""The full multi-view UNet model with attention, timestep embedding and camera embedding.:param in_channels: channels in the input Tensor.:param model_channels: base channel count for the model.:param out_channels: channels in the output Tensor.:param num_res_blocks: number of residual blocks per downsample.:param attention_resolutions: a collection of downsample rates at whichattention will take place. May be a set, list, or tuple.For example, if this contains 4, then at 4x downsampling, attentionwill be used.:param dropout: the dropout probability.:param channel_mult: channel multiplier for each level of the UNet.:param conv_resample: if True, use learned convolutions for upsampling anddownsampling.:param dims: determines if the signal is 1D, 2D, or 3D.:param num_classes: if specified (as an int), then this model will beclass-conditional with `num_classes` classes.:param num_heads: the number of attention heads in each attention layer.:param num_heads_channels: if specified, ignore num_heads and instead usea fixed channel width per attention head.:param num_heads_upsample: works with num_heads to set a different numberof heads for upsampling. Deprecated.:param use_scale_shift_norm: use a FiLM-like conditioning mechanism.:param resblock_updown: use residual blocks for up/downsampling.:param use_new_attention_order: use a different attention pattern for potentiallyincreased efficiency.:param camera_dim: dimensionality of camera input."""def __init__(self,image_size,in_channels,model_channels,out_channels,num_res_blocks,attention_resolutions,dropout=0,channel_mult=(1, 2, 4, 8),conv_resample=True,dims=2,num_classes=None,num_heads=-1,num_head_channels=-1,num_heads_upsample=-1,use_scale_shift_norm=False,resblock_updown=False,transformer_depth=1,context_dim=None,n_embed=None,num_attention_blocks=None,adm_in_channels=None,camera_dim=None,ip_dim=0, # imagedream uses ip_dim > 0ip_weight=1.0,**kwargs,):super().__init__()assert context_dim is not Noneif num_heads_upsample == -1:num_heads_upsample = num_headsif num_heads == -1:assert (num_head_channels != -1), "Either num_heads or num_head_channels has to be set"if num_head_channels == -1:assert (num_heads != -1), "Either num_heads or num_head_channels has to be set"self.image_size = image_sizeself.in_channels = in_channelsself.model_channels = model_channelsself.out_channels = out_channelsif isinstance(num_res_blocks, int):self.num_res_blocks = len(channel_mult) * [num_res_blocks]else:if len(num_res_blocks) != len(channel_mult):raise ValueError("provide num_res_blocks either as an int (globally constant) or ""as a list/tuple (per-level) with the same length as channel_mult")self.num_res_blocks = num_res_blocksif num_attention_blocks is not None:assert len(num_attention_blocks) == len(self.num_res_blocks)assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i],range(len(num_attention_blocks)),))print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "f"This option has LESS priority than attention_resolutions {attention_resolutions}, "f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "f"attention will still not be set.")self.attention_resolutions = attention_resolutionsself.dropout = dropoutself.channel_mult = channel_multself.conv_resample = conv_resampleself.num_classes = num_classesself.num_heads = num_headsself.num_head_channels = num_head_channelsself.num_heads_upsample = num_heads_upsampleself.predict_codebook_ids = n_embed is not Noneself.ip_dim = ip_dimself.ip_weight = ip_weightif self.ip_dim > 0:self.image_embed = Resampler(dim=context_dim,depth=4,dim_head=64,heads=12,num_queries=ip_dim, # num tokenembedding_dim=1280,output_dim=context_dim,ff_mult=4,)time_embed_dim = model_channels * 4self.time_embed = nn.Sequential(nn.Linear(model_channels, time_embed_dim),nn.SiLU(),nn.Linear(time_embed_dim, time_embed_dim),)if camera_dim is not None:time_embed_dim = model_channels * 4self.camera_embed = nn.Sequential(nn.Linear(camera_dim, time_embed_dim),nn.SiLU(),nn.Linear(time_embed_dim, time_embed_dim),)if self.num_classes is not None:if isinstance(self.num_classes, int):self.label_emb = nn.Embedding(self.num_classes, time_embed_dim)elif self.num_classes == "continuous":# print("setting up linear c_adm embedding layer")self.label_emb = nn.Linear(1, time_embed_dim)elif self.num_classes == "sequential":assert adm_in_channels is not Noneself.label_emb = nn.Sequential(nn.Sequential(nn.Linear(adm_in_channels, time_embed_dim),nn.SiLU(),nn.Linear(time_embed_dim, time_embed_dim),))else:raise ValueError()self.input_blocks = nn.ModuleList([CondSequential(conv_nd(dims, in_channels, model_channels, 3, padding=1))])self._feature_size = model_channelsinput_block_chans = [model_channels]ch = model_channelsds = 1for level, mult in enumerate(channel_mult):for nr in range(self.num_res_blocks[level]):layers: List[Any] = [ResBlock(ch,time_embed_dim,dropout,out_channels=mult * model_channels,dims=dims,use_scale_shift_norm=use_scale_shift_norm,)]ch = mult * model_channelsif ds in attention_resolutions:if num_head_channels == -1:dim_head = ch // num_headselse:num_heads = ch // num_head_channelsdim_head = num_head_channelsif num_attention_blocks is None or nr < num_attention_blocks[level]:layers.append(SpatialTransformer3D(ch,num_heads,dim_head,context_dim=context_dim,depth=transformer_depth,ip_dim=self.ip_dim,ip_weight=self.ip_weight,))self.input_blocks.append(CondSequential(*layers))self._feature_size += chinput_block_chans.append(ch)if level != len(channel_mult) - 1:out_ch = chself.input_blocks.append(CondSequential(ResBlock(ch,time_embed_dim,dropout,out_channels=out_ch,dims=dims,use_scale_shift_norm=use_scale_shift_norm,down=True,)if resblock_updownelse Downsample(ch, conv_resample, dims=dims, out_channels=out_ch)))ch = out_chinput_block_chans.append(ch)ds *= 2self._feature_size += chif num_head_channels == -1:dim_head = ch // num_headselse:num_heads = ch // num_head_channelsdim_head = num_head_channelsself.middle_block = CondSequential(ResBlock(ch,time_embed_dim,dropout,dims=dims,use_scale_shift_norm=use_scale_shift_norm,),SpatialTransformer3D(ch,num_heads,dim_head,context_dim=context_dim,depth=transformer_depth,ip_dim=self.ip_dim,ip_weight=self.ip_weight,),ResBlock(ch,time_embed_dim,dropout,dims=dims,use_scale_shift_norm=use_scale_shift_norm,),)self._feature_size += chself.output_blocks = nn.ModuleList([])for level, mult in list(enumerate(channel_mult))[::-1]:for i in range(self.num_res_blocks[level] + 1):ich = input_block_chans.pop()layers = [ResBlock(ch + ich,time_embed_dim,dropout,out_channels=model_channels * mult,dims=dims,use_scale_shift_norm=use_scale_shift_norm,)]ch = model_channels * multif ds in attention_resolutions:if num_head_channels == -1:dim_head = ch // num_headselse:num_heads = ch // num_head_channelsdim_head = num_head_channelsif num_attention_blocks is None or i < num_attention_blocks[level]:layers.append(SpatialTransformer3D(ch,num_heads,dim_head,context_dim=context_dim,depth=transformer_depth,ip_dim=self.ip_dim,ip_weight=self.ip_weight,))if level and i == self.num_res_blocks[level]:out_ch = chlayers.append(ResBlock(ch,time_embed_dim,dropout,out_channels=out_ch,dims=dims,use_scale_shift_norm=use_scale_shift_norm,up=True,)if resblock_updownelse Upsample(ch, conv_resample, dims=dims, out_channels=out_ch))ds //= 2self.output_blocks.append(CondSequential(*layers))self._feature_size += chself.out = nn.Sequential(nn.GroupNorm(32, ch),nn.SiLU(),zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),)if self.predict_codebook_ids:self.id_predictor = nn.Sequential(nn.GroupNorm(32, ch),conv_nd(dims, model_channels, n_embed, 1),# nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits)def forward(self,x,timesteps=None,context=None,y=None,camera=None,num_frames=1,ip=None,ip_img=None,**kwargs,):"""Apply the model to an input batch.:param x: an [(N x F) x C x ...] Tensor of inputs. F is the number of frames (views).:param timesteps: a 1-D batch of timesteps.:param context: conditioning plugged in via crossattn:param y: an [N] Tensor of labels, if class-conditional.:param num_frames: a integer indicating number of frames for tensor reshaping.:return: an [(N x F) x C x ...] Tensor of outputs. F is the number of frames (views)."""assert (x.shape[0] % num_frames == 0), "input batch size must be dividable by num_frames!"assert (y is not None) == (self.num_classes is not None), "must specify y if and only if the model is class-conditional"hs = []t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)emb = self.time_embed(t_emb)if self.num_classes is not None:assert y is not Noneassert y.shape[0] == x.shape[0]emb = emb + self.label_emb(y)# Add camera embeddingsif camera is not None:emb = emb + self.camera_embed(camera)# imagedream variantif self.ip_dim > 0:x[(num_frames - 1) :: num_frames, :, :, :] = ip_img # place at [4, 9]ip_emb = self.image_embed(ip)context = torch.cat((context, ip_emb), 1)h = xfor module in self.input_blocks:h = module(h, emb, context, num_frames=num_frames)hs.append(h)h = self.middle_block(h, emb, context, num_frames=num_frames)for module in self.output_blocks:h = torch.cat([h, hs.pop()], dim=1)h = module(h, emb, context, num_frames=num_frames)h = h.type(x.dtype)if self.predict_codebook_ids:return self.id_predictor(h)else:return self.out(h)logger = logging.get_logger(__name__) # pylint: disable=invalid-name382 unmodified linesif image.dtype == np.float32:image = (image * 255).astype(np.uint8)image = self.feature_extractor(image, return_tensors="pt").pixel_valuesimage = image.to(device=device, dtype=dtype)image_embeds = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)return torch.zeros_like(image_embeds), image_embedsdef encode_image_latents(self, image, device, num_images_per_prompt):dtype = next(self.image_encoder.parameters()).dtypeimage = (torch.from_numpy(image).unsqueeze(0).permute(0, 3, 1, 2).to(device=device)) # [1, 3, H, W]image = 2 * image - 1image = F.interpolate(image, (256, 256), mode="bilinear", align_corners=False)image = image.to(dtype=dtype)posterior = self.vae.encode(image).latent_distlatents = posterior.sample() * self.vae.config.scaling_factor # [B, C, H, W]latents = latents.repeat_interleave(num_images_per_prompt, dim=0)return torch.zeros_like(latents), latents12 unmodified linesnum_images_per_prompt: int = 1,eta: float = 0.0,generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,output_type: Optional[str] = "numpy", # pil, numpy, latentscallback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,callback_steps: int = 1,num_frames: int = 4,16 unmodified linesif image is not None:assert isinstance(image, np.ndarray) and image.dtype == np.float32self.image_encoder = self.image_encoder.to(device=device)image_embeds_neg, image_embeds_pos = self.encode_image(image, device, num_images_per_prompt)image_latents_neg, image_latents_pos = self.encode_image_latents(image, device, num_images_per_prompt)_prompt_embeds = self._encode_prompt(prompt=prompt,device=device,17 unmodified lines)# Get cameracamera = get_camera(num_frames, elevation=elevation, extra_view=(image is not None)).to(dtype=latents.dtype, device=device)camera = camera.repeat_interleave(num_images_per_prompt, dim=0)# Prepare extra step kwargs.6 unmodified lines# expand the latents if we are doing classifier free guidancemultiplier = 2 if do_classifier_free_guidance else 1latent_model_input = torch.cat([latents] * multiplier)latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)unet_inputs = {"x": latent_model_input,"timesteps": torch.tensor([t] * actual_num_frames * multiplier,dtype=latent_model_input.dtype,device=device,),"context": torch.cat([prompt_embeds_neg] * actual_num_frames+ [prompt_embeds_pos] * actual_num_frames),"num_frames": actual_num_frames,"camera": torch.cat([camera] * multiplier),}if image is not None:unet_inputs["ip"] = torch.cat([image_embeds_neg] * actual_num_frames+ [image_embeds_pos] * actual_num_frames)unet_inputs["ip_img"] = torch.cat([image_latents_neg] + [image_latents_pos]) # no repeat# predict the noise residualnoise_pred = self.unet.forward(**unet_inputs)23 unmodified lineselif output_type == "pil":image = self.decode_latents(latents)image = self.numpy_to_pil(image)else: # numpyimage = self.decode_latents(latents)# Offload last model to CPU
mv_unet.pyDeleted-1005
pipeline.py+1064-25