mirror of
https://github.com/lucidrains/DALLE2-pytorch.git
synced 2026-02-14 10:24:31 +01:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d67d5821e | ||
|
|
748c7fe7af | ||
|
|
80046334ad |
14
README.md
14
README.md
@@ -396,7 +396,7 @@ decoder = Decoder(
|
|||||||
).cuda()
|
).cuda()
|
||||||
|
|
||||||
for unet_number in (1, 2):
|
for unet_number in (1, 2):
|
||||||
loss = decoder(images, unet_number = unet_number) # this can optionally be decoder(images, text) if you wish to condition on the text encodings as well, though it was hinted in the paper it didn't do much
|
loss = decoder(images, text = text, unet_number = unet_number) # this can optionally be decoder(images, text) if you wish to condition on the text encodings as well, though it was hinted in the paper it didn't do much
|
||||||
loss.backward()
|
loss.backward()
|
||||||
|
|
||||||
# do above for many steps
|
# do above for many steps
|
||||||
@@ -861,25 +861,23 @@ unet1 = Unet(
|
|||||||
text_embed_dim = 512,
|
text_embed_dim = 512,
|
||||||
cond_dim = 128,
|
cond_dim = 128,
|
||||||
channels = 3,
|
channels = 3,
|
||||||
dim_mults=(1, 2, 4, 8)
|
dim_mults=(1, 2, 4, 8),
|
||||||
|
cond_on_text_encodings = True,
|
||||||
).cuda()
|
).cuda()
|
||||||
|
|
||||||
unet2 = Unet(
|
unet2 = Unet(
|
||||||
dim = 16,
|
dim = 16,
|
||||||
image_embed_dim = 512,
|
image_embed_dim = 512,
|
||||||
text_embed_dim = 512,
|
|
||||||
cond_dim = 128,
|
cond_dim = 128,
|
||||||
channels = 3,
|
channels = 3,
|
||||||
dim_mults = (1, 2, 4, 8, 16),
|
dim_mults = (1, 2, 4, 8, 16),
|
||||||
cond_on_text_encodings = True
|
|
||||||
).cuda()
|
).cuda()
|
||||||
|
|
||||||
decoder = Decoder(
|
decoder = Decoder(
|
||||||
unet = (unet1, unet2),
|
unet = (unet1, unet2),
|
||||||
image_sizes = (128, 256),
|
image_sizes = (128, 256),
|
||||||
clip = clip,
|
clip = clip,
|
||||||
timesteps = 1000,
|
timesteps = 1000
|
||||||
condition_on_text_encodings = True
|
|
||||||
).cuda()
|
).cuda()
|
||||||
|
|
||||||
decoder_trainer = DecoderTrainer(
|
decoder_trainer = DecoderTrainer(
|
||||||
@@ -904,8 +902,8 @@ for unet_number in (1, 2):
|
|||||||
# after much training
|
# after much training
|
||||||
# you can sample from the exponentially moving averaged unets as so
|
# you can sample from the exponentially moving averaged unets as so
|
||||||
|
|
||||||
mock_image_embed = torch.randn(4, 512).cuda()
|
mock_image_embed = torch.randn(32, 512).cuda()
|
||||||
images = decoder_trainer.sample(mock_image_embed, text = text) # (4, 3, 256, 256)
|
images = decoder_trainer.sample(image_embed = mock_image_embed, text = text) # (4, 3, 256, 256)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Diffusion Prior Training
|
### Diffusion Prior Training
|
||||||
|
|||||||
@@ -547,34 +547,40 @@ class NoiseScheduler(nn.Module):
|
|||||||
# diffusion prior
|
# diffusion prior
|
||||||
|
|
||||||
class LayerNorm(nn.Module):
|
class LayerNorm(nn.Module):
|
||||||
def __init__(self, dim, eps = 1e-5, stable = False):
|
def __init__(self, dim, eps = 1e-5, fp16_eps = 1e-3, stable = False):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.eps = eps
|
self.eps = eps
|
||||||
|
self.fp16_eps = fp16_eps
|
||||||
self.stable = stable
|
self.stable = stable
|
||||||
self.g = nn.Parameter(torch.ones(dim))
|
self.g = nn.Parameter(torch.ones(dim))
|
||||||
|
|
||||||
def forward(self, x):
|
def forward(self, x):
|
||||||
|
eps = self.eps if x.dtype == torch.float32 else self.fp16_eps
|
||||||
|
|
||||||
if self.stable:
|
if self.stable:
|
||||||
x = x / x.amax(dim = -1, keepdim = True).detach()
|
x = x / x.amax(dim = -1, keepdim = True).detach()
|
||||||
|
|
||||||
var = torch.var(x, dim = -1, unbiased = False, keepdim = True)
|
var = torch.var(x, dim = -1, unbiased = False, keepdim = True)
|
||||||
mean = torch.mean(x, dim = -1, keepdim = True)
|
mean = torch.mean(x, dim = -1, keepdim = True)
|
||||||
return (x - mean) * (var + self.eps).rsqrt() * self.g
|
return (x - mean) * (var + eps).rsqrt() * self.g
|
||||||
|
|
||||||
class ChanLayerNorm(nn.Module):
|
class ChanLayerNorm(nn.Module):
|
||||||
def __init__(self, dim, eps = 1e-5, stable = False):
|
def __init__(self, dim, eps = 1e-5, fp16_eps = 1e-3, stable = False):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.eps = eps
|
self.eps = eps
|
||||||
|
self.fp16_eps = fp16_eps
|
||||||
self.stable = stable
|
self.stable = stable
|
||||||
self.g = nn.Parameter(torch.ones(1, dim, 1, 1))
|
self.g = nn.Parameter(torch.ones(1, dim, 1, 1))
|
||||||
|
|
||||||
def forward(self, x):
|
def forward(self, x):
|
||||||
|
eps = self.eps if x.dtype == torch.float32 else self.fp16_eps
|
||||||
|
|
||||||
if self.stable:
|
if self.stable:
|
||||||
x = x / x.amax(dim = 1, keepdim = True).detach()
|
x = x / x.amax(dim = 1, keepdim = True).detach()
|
||||||
|
|
||||||
var = torch.var(x, dim = 1, unbiased = False, keepdim = True)
|
var = torch.var(x, dim = 1, unbiased = False, keepdim = True)
|
||||||
mean = torch.mean(x, dim = 1, keepdim = True)
|
mean = torch.mean(x, dim = 1, keepdim = True)
|
||||||
return (x - mean) * (var + self.eps).rsqrt() * self.g
|
return (x - mean) * (var + eps).rsqrt() * self.g
|
||||||
|
|
||||||
class Residual(nn.Module):
|
class Residual(nn.Module):
|
||||||
def __init__(self, fn):
|
def __init__(self, fn):
|
||||||
@@ -1357,7 +1363,8 @@ class ResnetBlock(nn.Module):
|
|||||||
*,
|
*,
|
||||||
cond_dim = None,
|
cond_dim = None,
|
||||||
time_cond_dim = None,
|
time_cond_dim = None,
|
||||||
groups = 8
|
groups = 8,
|
||||||
|
cosine_sim_cross_attn = False
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
@@ -1377,7 +1384,8 @@ class ResnetBlock(nn.Module):
|
|||||||
'b (h w) c',
|
'b (h w) c',
|
||||||
CrossAttention(
|
CrossAttention(
|
||||||
dim = dim_out,
|
dim = dim_out,
|
||||||
context_dim = cond_dim
|
context_dim = cond_dim,
|
||||||
|
cosine_sim = cosine_sim_cross_attn
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -1412,11 +1420,12 @@ class CrossAttention(nn.Module):
|
|||||||
heads = 8,
|
heads = 8,
|
||||||
dropout = 0.,
|
dropout = 0.,
|
||||||
norm_context = False,
|
norm_context = False,
|
||||||
pb_relax_alpha = 32 ** 2
|
cosine_sim = False,
|
||||||
|
cosine_sim_scale = 16
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.pb_relax_alpha = pb_relax_alpha
|
self.cosine_sim = cosine_sim
|
||||||
self.scale = dim_head ** -0.5 * (pb_relax_alpha ** -1)
|
self.scale = cosine_sim_scale if cosine_sim else (dim_head ** -0.5)
|
||||||
self.heads = heads
|
self.heads = heads
|
||||||
inner_dim = dim_head * heads
|
inner_dim = dim_head * heads
|
||||||
|
|
||||||
@@ -1452,7 +1461,10 @@ class CrossAttention(nn.Module):
|
|||||||
k = torch.cat((nk, k), dim = -2)
|
k = torch.cat((nk, k), dim = -2)
|
||||||
v = torch.cat((nv, v), dim = -2)
|
v = torch.cat((nv, v), dim = -2)
|
||||||
|
|
||||||
q = q * self.scale
|
if self.cosine_sim:
|
||||||
|
q, k = map(l2norm, (q, k))
|
||||||
|
|
||||||
|
q, k = map(lambda t: t * math.sqrt(self.scale), (q, k))
|
||||||
|
|
||||||
sim = einsum('b h i d, b h j d -> b h i j', q, k)
|
sim = einsum('b h i d, b h j d -> b h i j', q, k)
|
||||||
max_neg_value = -torch.finfo(sim.dtype).max
|
max_neg_value = -torch.finfo(sim.dtype).max
|
||||||
@@ -1462,9 +1474,6 @@ class CrossAttention(nn.Module):
|
|||||||
mask = rearrange(mask, 'b j -> b 1 1 j')
|
mask = rearrange(mask, 'b j -> b 1 1 j')
|
||||||
sim = sim.masked_fill(~mask, max_neg_value)
|
sim = sim.masked_fill(~mask, max_neg_value)
|
||||||
|
|
||||||
sim = sim - sim.amax(dim = -1, keepdim = True).detach()
|
|
||||||
sim = sim * self.pb_relax_alpha
|
|
||||||
|
|
||||||
attn = sim.softmax(dim = -1)
|
attn = sim.softmax(dim = -1)
|
||||||
|
|
||||||
out = einsum('b h i j, b h j d -> b h i d', attn, v)
|
out = einsum('b h i j, b h j d -> b h i d', attn, v)
|
||||||
@@ -1494,6 +1503,7 @@ class LinearAttention(nn.Module):
|
|||||||
|
|
||||||
def forward(self, fmap):
|
def forward(self, fmap):
|
||||||
h, x, y = self.heads, *fmap.shape[-2:]
|
h, x, y = self.heads, *fmap.shape[-2:]
|
||||||
|
seq_len = x * y
|
||||||
|
|
||||||
fmap = self.norm(fmap)
|
fmap = self.norm(fmap)
|
||||||
q, k, v = self.to_qkv(fmap).chunk(3, dim = 1)
|
q, k, v = self.to_qkv(fmap).chunk(3, dim = 1)
|
||||||
@@ -1503,7 +1513,9 @@ class LinearAttention(nn.Module):
|
|||||||
k = k.softmax(dim = -2)
|
k = k.softmax(dim = -2)
|
||||||
|
|
||||||
q = q * self.scale
|
q = q * self.scale
|
||||||
v = v / (x * y)
|
v = l2norm(v)
|
||||||
|
|
||||||
|
k, v = map(lambda t: t / math.sqrt(seq_len), (k, v))
|
||||||
|
|
||||||
context = einsum('b n d, b n e -> b d e', k, v)
|
context = einsum('b n d, b n e -> b d e', k, v)
|
||||||
out = einsum('b n d, b d e -> b n e', q, context)
|
out = einsum('b n d, b d e -> b n e', q, context)
|
||||||
@@ -1591,6 +1603,7 @@ class Unet(nn.Module):
|
|||||||
lowres_cond = False, # for cascading diffusion - https://cascaded-diffusion.github.io/
|
lowres_cond = False, # for cascading diffusion - https://cascaded-diffusion.github.io/
|
||||||
lowres_noise_cond = False, # for conditioning on low resolution noising, based on Imagen
|
lowres_noise_cond = False, # for conditioning on low resolution noising, based on Imagen
|
||||||
sparse_attn = False,
|
sparse_attn = False,
|
||||||
|
cosine_sim_cross_attn = False,
|
||||||
attend_at_middle = True, # whether to have a layer of attention at the bottleneck (can turn off for higher resolution in cascading DDPM, before bringing in efficient attention)
|
attend_at_middle = True, # whether to have a layer of attention at the bottleneck (can turn off for higher resolution in cascading DDPM, before bringing in efficient attention)
|
||||||
cond_on_text_encodings = False,
|
cond_on_text_encodings = False,
|
||||||
max_text_len = 256,
|
max_text_len = 256,
|
||||||
@@ -1734,9 +1747,13 @@ class Unet(nn.Module):
|
|||||||
|
|
||||||
upsample_klass = NearestUpsample if not pixel_shuffle_upsample else PixelShuffleUpsample
|
upsample_klass = NearestUpsample if not pixel_shuffle_upsample else PixelShuffleUpsample
|
||||||
|
|
||||||
|
# prepare resnet klass
|
||||||
|
|
||||||
|
resnet_block = partial(ResnetBlock, cosine_sim_cross_attn = cosine_sim_cross_attn)
|
||||||
|
|
||||||
# give memory efficient unet an initial resnet block
|
# give memory efficient unet an initial resnet block
|
||||||
|
|
||||||
self.init_resnet_block = ResnetBlock(init_dim, init_dim, time_cond_dim = time_cond_dim, groups = top_level_resnet_group) if memory_efficient else None
|
self.init_resnet_block = resnet_block(init_dim, init_dim, time_cond_dim = time_cond_dim, groups = top_level_resnet_group) if memory_efficient else None
|
||||||
|
|
||||||
# layers
|
# layers
|
||||||
|
|
||||||
@@ -1763,17 +1780,17 @@ class Unet(nn.Module):
|
|||||||
|
|
||||||
self.downs.append(nn.ModuleList([
|
self.downs.append(nn.ModuleList([
|
||||||
downsample_klass(dim_in, dim_out = dim_out) if memory_efficient else None,
|
downsample_klass(dim_in, dim_out = dim_out) if memory_efficient else None,
|
||||||
ResnetBlock(dim_layer, dim_layer, time_cond_dim = time_cond_dim, groups = groups),
|
resnet_block(dim_layer, dim_layer, time_cond_dim = time_cond_dim, groups = groups),
|
||||||
nn.ModuleList([ResnetBlock(dim_layer, dim_layer, cond_dim = layer_cond_dim, time_cond_dim = time_cond_dim, groups = groups) for _ in range(layer_num_resnet_blocks)]),
|
nn.ModuleList([resnet_block(dim_layer, dim_layer, cond_dim = layer_cond_dim, time_cond_dim = time_cond_dim, groups = groups) for _ in range(layer_num_resnet_blocks)]),
|
||||||
attention,
|
attention,
|
||||||
downsample_klass(dim_layer, dim_out = dim_out) if not is_last and not memory_efficient else nn.Conv2d(dim_layer, dim_out, 1)
|
downsample_klass(dim_layer, dim_out = dim_out) if not is_last and not memory_efficient else nn.Conv2d(dim_layer, dim_out, 1)
|
||||||
]))
|
]))
|
||||||
|
|
||||||
mid_dim = dims[-1]
|
mid_dim = dims[-1]
|
||||||
|
|
||||||
self.mid_block1 = ResnetBlock(mid_dim, mid_dim, cond_dim = cond_dim, time_cond_dim = time_cond_dim, groups = resnet_groups[-1])
|
self.mid_block1 = resnet_block(mid_dim, mid_dim, cond_dim = cond_dim, time_cond_dim = time_cond_dim, groups = resnet_groups[-1])
|
||||||
self.mid_attn = create_self_attn(mid_dim)
|
self.mid_attn = create_self_attn(mid_dim)
|
||||||
self.mid_block2 = ResnetBlock(mid_dim, mid_dim, cond_dim = cond_dim, time_cond_dim = time_cond_dim, groups = resnet_groups[-1])
|
self.mid_block2 = resnet_block(mid_dim, mid_dim, cond_dim = cond_dim, time_cond_dim = time_cond_dim, groups = resnet_groups[-1])
|
||||||
|
|
||||||
for ind, ((dim_in, dim_out), groups, layer_num_resnet_blocks, layer_self_attn) in enumerate(zip(reversed(in_out), reversed(resnet_groups), reversed(num_resnet_blocks), reversed(self_attn))):
|
for ind, ((dim_in, dim_out), groups, layer_num_resnet_blocks, layer_self_attn) in enumerate(zip(reversed(in_out), reversed(resnet_groups), reversed(num_resnet_blocks), reversed(self_attn))):
|
||||||
is_last = ind >= (len(in_out) - 1)
|
is_last = ind >= (len(in_out) - 1)
|
||||||
@@ -1790,8 +1807,8 @@ class Unet(nn.Module):
|
|||||||
upsample_combiner_dims.append(dim_out)
|
upsample_combiner_dims.append(dim_out)
|
||||||
|
|
||||||
self.ups.append(nn.ModuleList([
|
self.ups.append(nn.ModuleList([
|
||||||
ResnetBlock(dim_out + skip_connect_dim, dim_out, cond_dim = layer_cond_dim, time_cond_dim = time_cond_dim, groups = groups),
|
resnet_block(dim_out + skip_connect_dim, dim_out, cond_dim = layer_cond_dim, time_cond_dim = time_cond_dim, groups = groups),
|
||||||
nn.ModuleList([ResnetBlock(dim_out + skip_connect_dim, dim_out, cond_dim = layer_cond_dim, time_cond_dim = time_cond_dim, groups = groups) for _ in range(layer_num_resnet_blocks)]),
|
nn.ModuleList([resnet_block(dim_out + skip_connect_dim, dim_out, cond_dim = layer_cond_dim, time_cond_dim = time_cond_dim, groups = groups) for _ in range(layer_num_resnet_blocks)]),
|
||||||
attention,
|
attention,
|
||||||
upsample_klass(dim_out, dim_in) if not is_last or memory_efficient else nn.Identity()
|
upsample_klass(dim_out, dim_in) if not is_last or memory_efficient else nn.Identity()
|
||||||
]))
|
]))
|
||||||
@@ -1807,7 +1824,7 @@ class Unet(nn.Module):
|
|||||||
|
|
||||||
# a final resnet block
|
# a final resnet block
|
||||||
|
|
||||||
self.final_resnet_block = ResnetBlock(self.upsample_combiner.dim_out + dim, dim, time_cond_dim = time_cond_dim, groups = top_level_resnet_group)
|
self.final_resnet_block = resnet_block(self.upsample_combiner.dim_out + dim, dim, time_cond_dim = time_cond_dim, groups = top_level_resnet_group)
|
||||||
|
|
||||||
out_dim_in = dim + (channels if lowres_cond else 0)
|
out_dim_in = dim + (channels if lowres_cond else 0)
|
||||||
|
|
||||||
@@ -1831,7 +1848,7 @@ class Unet(nn.Module):
|
|||||||
channels == self.channels and \
|
channels == self.channels and \
|
||||||
cond_on_image_embeds == self.cond_on_image_embeds and \
|
cond_on_image_embeds == self.cond_on_image_embeds and \
|
||||||
cond_on_text_encodings == self.cond_on_text_encodings and \
|
cond_on_text_encodings == self.cond_on_text_encodings and \
|
||||||
cond_on_lowres_noise == self.cond_on_lowres_noise and \
|
lowres_noise_cond == self.lowres_noise_cond and \
|
||||||
channels_out == self.channels_out:
|
channels_out == self.channels_out:
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
|||||||
@@ -174,7 +174,7 @@ class DiffusionPriorTrainer(nn.Module):
|
|||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
diffusion_prior,
|
diffusion_prior,
|
||||||
accelerator,
|
accelerator = None,
|
||||||
use_ema = True,
|
use_ema = True,
|
||||||
lr = 3e-4,
|
lr = 3e-4,
|
||||||
wd = 1e-2,
|
wd = 1e-2,
|
||||||
@@ -186,8 +186,12 @@ class DiffusionPriorTrainer(nn.Module):
|
|||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
assert isinstance(diffusion_prior, DiffusionPrior)
|
assert isinstance(diffusion_prior, DiffusionPrior)
|
||||||
assert isinstance(accelerator, Accelerator)
|
|
||||||
ema_kwargs, kwargs = groupby_prefix_and_trim('ema_', kwargs)
|
ema_kwargs, kwargs = groupby_prefix_and_trim('ema_', kwargs)
|
||||||
|
accelerator_kwargs, kwargs = groupby_prefix_and_trim('accelerator_', kwargs)
|
||||||
|
|
||||||
|
if not exists(accelerator):
|
||||||
|
accelerator = Accelerator(**accelerator_kwargs)
|
||||||
|
|
||||||
# assign some helpful member vars
|
# assign some helpful member vars
|
||||||
|
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
__version__ = '1.2.1'
|
__version__ = '1.4.2'
|
||||||
|
|||||||
Reference in New Issue
Block a user