Delete models
Browse files- models/diffusion.py +0 -312
- models/dit.py +0 -369
- models/ema.py +0 -97
models/diffusion.py
DELETED
|
@@ -1,312 +0,0 @@
|
|
| 1 |
-
import itertools
|
| 2 |
-
import math
|
| 3 |
-
import torch
|
| 4 |
-
import numpy as np
|
| 5 |
-
import pytorch_lightning as L
|
| 6 |
-
import torchmetrics
|
| 7 |
-
from dataclasses import dataclass
|
| 8 |
-
import dit, ema
|
| 9 |
-
import noise_schedule # Assuming this is part of the MDLM repository
|
| 10 |
-
|
| 11 |
-
LOG2 = math.log(2)
|
| 12 |
-
|
| 13 |
-
@dataclass
|
| 14 |
-
class Loss:
|
| 15 |
-
loss: torch.FloatTensor
|
| 16 |
-
nlls: torch.FloatTensor
|
| 17 |
-
token_mask: torch.FloatTensor
|
| 18 |
-
|
| 19 |
-
class NLL(torchmetrics.MeanMetric):
|
| 20 |
-
pass
|
| 21 |
-
|
| 22 |
-
class BPD(NLL):
|
| 23 |
-
def compute(self) -> torch.Tensor:
|
| 24 |
-
"""Computes the bits per dimension.
|
| 25 |
-
Returns:
|
| 26 |
-
bpd
|
| 27 |
-
"""
|
| 28 |
-
return self.mean_value / self.weight / LOG2
|
| 29 |
-
|
| 30 |
-
class Perplexity(NLL):
|
| 31 |
-
def compute(self) -> torch.Tensor:
|
| 32 |
-
"""Computes the Perplexity.
|
| 33 |
-
Returns:
|
| 34 |
-
Perplexity
|
| 35 |
-
"""
|
| 36 |
-
return torch.exp(self.mean_value / self.weight)
|
| 37 |
-
|
| 38 |
-
# Based on MDLM repo
|
| 39 |
-
class Diffusion(L.LightningModule):
|
| 40 |
-
def __init__(self, config, latent_dim, tokenizer):
|
| 41 |
-
super().__init__()
|
| 42 |
-
self.config = config
|
| 43 |
-
self.latent_dim = latent_dim
|
| 44 |
-
self.tokenizer = tokenizer
|
| 45 |
-
|
| 46 |
-
self.backbone = dit.DIT(self.config, vocab_size=self.latent_dim)
|
| 47 |
-
self.T = self.config.T
|
| 48 |
-
self.subs_masking = self.config.SUBS_MASKING
|
| 49 |
-
self.antithetic_sampling = self.config.Training.ANTITHETIC_SAMPLING
|
| 50 |
-
self.mask_index = self.tokenizer.mask_token_id
|
| 51 |
-
|
| 52 |
-
self.softplus = torch.nn.Softplus()
|
| 53 |
-
metrics = torchmetrics.MetricCollection({
|
| 54 |
-
'nll': NLL(),
|
| 55 |
-
'bpd': BPD(),
|
| 56 |
-
'ppl': Perplexity(),
|
| 57 |
-
})
|
| 58 |
-
metrics.set_dtype(torch.float64)
|
| 59 |
-
self.train_metrics = metrics.clone(prefix='train/')
|
| 60 |
-
self.valid_metrics = metrics.clone(prefix='val/')
|
| 61 |
-
self.test_metrics = metrics.clone(prefix='test/')
|
| 62 |
-
|
| 63 |
-
self.noise = noise_schedule.get_noise(self.config, dtype=self.dtype)
|
| 64 |
-
self.lr = self.config.Optim.LR
|
| 65 |
-
self.sampling_eps = self.config.Training.SAMPLING_EPS
|
| 66 |
-
self.time_conditioning = self.config.TIME_CONDITIONING
|
| 67 |
-
self.neg_infinity = -1000000.0
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
############ FORWARD DIFFUSION #########
|
| 71 |
-
def subs_parameterization(self, logits, noised_latents):
|
| 72 |
-
# log prob at the mask index = - infinity
|
| 73 |
-
logits[:, :, self.mask_index] += self.neg_infinity
|
| 74 |
-
|
| 75 |
-
# Normalize the logits such that x.exp() is
|
| 76 |
-
# a probability distribution over vocab_size.
|
| 77 |
-
logits = logits - torch.logsumexp(logits, dim=-1,
|
| 78 |
-
keepdim=True)
|
| 79 |
-
|
| 80 |
-
# Apply updates directly in the logits matrix.
|
| 81 |
-
# For the logits of the unmasked tokens, set all values
|
| 82 |
-
# to -infinity except for the indices corresponding to
|
| 83 |
-
# the unmasked tokens.
|
| 84 |
-
unmasked_indices = (noised_latents != self.mask_index)
|
| 85 |
-
logits[unmasked_indices] = self.neg_infinity
|
| 86 |
-
logits[unmasked_indices, noised_latents[unmasked_indices]] = 0
|
| 87 |
-
return logits
|
| 88 |
-
|
| 89 |
-
def forward(self, latents, sigma):
|
| 90 |
-
latents = latents.long()
|
| 91 |
-
with torch.cuda.amp.autocast(dtype=torch.float32):
|
| 92 |
-
logits = self.backbone(latents, sigma)
|
| 93 |
-
print(logits)
|
| 94 |
-
optimized_logits = self.subs_parameterization(logits, latents)
|
| 95 |
-
return optimized_logits
|
| 96 |
-
|
| 97 |
-
def q_xt(self, latents, move_chance):
|
| 98 |
-
"""
|
| 99 |
-
Computes the noisy sample xt.
|
| 100 |
-
Args:
|
| 101 |
-
x: int torch.Tensor with shape (batch_size, diffusion_model_input_length), input.
|
| 102 |
-
move_chance: float torch.Tensor with shape (batch_size, 1).
|
| 103 |
-
"""
|
| 104 |
-
latents = latents.mean(dim=1) # [bsz x seq_len x 1280] --> [bsz x 1280] as per args
|
| 105 |
-
move_indices = torch.rand(* latents.shape, device=latents.device) < move_chance
|
| 106 |
-
noised_latents = torch.where(move_indices, self.mask_index, latents)
|
| 107 |
-
return noised_latents
|
| 108 |
-
|
| 109 |
-
def sample_timestep(self, n, device):
|
| 110 |
-
_eps_t = torch.rand(n, device=device)
|
| 111 |
-
if self.antithetic_sampling:
|
| 112 |
-
offset = torch.arange(n, device=device) / n
|
| 113 |
-
_eps_t = (_eps_t / n + offset) % 1
|
| 114 |
-
t = (1 - self.sampling_eps) * _eps_t + self.sampling_eps
|
| 115 |
-
# if self.importance_sampling:
|
| 116 |
-
# return self.noise.importance_sampling_transformation(t)
|
| 117 |
-
return t
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
def d3pm_loss(self, model_output, xt, x0, t):
|
| 121 |
-
"""Computes the D3PM loss between noisy latents and the original input at a given time step."""
|
| 122 |
-
dt = 1 / self.T
|
| 123 |
-
|
| 124 |
-
if torch.is_tensor(t):
|
| 125 |
-
t = t[:, None]
|
| 126 |
-
assert t.ndim == 2
|
| 127 |
-
t = t.clamp(0., 1. - 1e-4)
|
| 128 |
-
alpha_t = 1 - t + torch.zeros_like(xt)
|
| 129 |
-
alpha_s = 1 - (t - dt) + torch.zeros_like(xt)
|
| 130 |
-
|
| 131 |
-
x0 = x0.to(torch.int64)
|
| 132 |
-
log_x_theta_at_x0 = torch.gather(model_output, -1, x0[:, :, None]).squeeze(-1)
|
| 133 |
-
log_x_theta_at_m = model_output[:, :, self.mask_index]
|
| 134 |
-
x_theta_at_m = log_x_theta_at_m.exp()
|
| 135 |
-
|
| 136 |
-
term_1_coef = dt / t
|
| 137 |
-
term_1_log_nr = torch.log(alpha_t * x_theta_at_m / t + 1)
|
| 138 |
-
term_1_log_dr = log_x_theta_at_x0
|
| 139 |
-
|
| 140 |
-
term_2_coef = 1 - dt / t
|
| 141 |
-
term_2_log_nr = term_1_log_nr
|
| 142 |
-
term_2_log_dr = torch.log(alpha_s * x_theta_at_m / (t - dt) + 1)
|
| 143 |
-
|
| 144 |
-
L_vb_masked = (
|
| 145 |
-
term_1_coef * (term_1_log_nr - term_1_log_dr)
|
| 146 |
-
+ term_2_coef * (term_2_log_nr - term_2_log_dr))
|
| 147 |
-
|
| 148 |
-
L_vb = L_vb_masked * (xt == self.mask_index)
|
| 149 |
-
|
| 150 |
-
return self.T * L_vb
|
| 151 |
-
|
| 152 |
-
def forward_diffusion(self, latents):
|
| 153 |
-
"""Forward diffusion process, adds noise to the latents."""
|
| 154 |
-
|
| 155 |
-
t = self.sample_timestep(latents.shape[0], latents.device)
|
| 156 |
-
if self.T > 0:
|
| 157 |
-
t = (t * self.T).to(torch.int)
|
| 158 |
-
t = t / self.T
|
| 159 |
-
# t \in {1/T, 2/T, ..., 1}
|
| 160 |
-
t += (1 / self.T)
|
| 161 |
-
|
| 162 |
-
sigma, dsigma = self.noise(t)
|
| 163 |
-
unet_conditioning = sigma[:, None]
|
| 164 |
-
move_chance = 1 - torch.exp(-sigma[:, None])
|
| 165 |
-
|
| 166 |
-
noised_latents = self.q_xt(latents, move_chance)
|
| 167 |
-
model_output = self.forward(noised_latents, unet_conditioning)
|
| 168 |
-
|
| 169 |
-
if self.T > 0:
|
| 170 |
-
diffusion_loss = self.d3pm_loss(model_output=model_output, xt=noised_latents, x0=latents, t=t)
|
| 171 |
-
return diffusion_loss
|
| 172 |
-
# SUBS parameterization, continuous time.
|
| 173 |
-
else:
|
| 174 |
-
log_p_theta = torch.gather(input=model_output, dim=-1, index=latents[:, :, None]).squeeze(-1)
|
| 175 |
-
return - log_p_theta * (dsigma / torch.expm1(sigma))[:, None]
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
######### LOSS CALCULATIONS #########
|
| 179 |
-
def maybe_sub_sample(self, x0, attention_mask):
|
| 180 |
-
# seqlen = x0.shape[1]
|
| 181 |
-
# print(seqlen)
|
| 182 |
-
# if seqlen > self.config.model.length:
|
| 183 |
-
# assert seqlen == 2 * self.config.model.length
|
| 184 |
-
# # cropping is needed for text8-crop dataset
|
| 185 |
-
# # try the same starting point for now
|
| 186 |
-
# start = np.random.choice(self.config.model.length)
|
| 187 |
-
# end = start + self.config.model.length
|
| 188 |
-
# input_tokens = x0[:, start: end]
|
| 189 |
-
# output_tokens = x0[:, start + 1: end + 1]
|
| 190 |
-
# new_attention_mask = attention_mask[:, start: end]
|
| 191 |
-
|
| 192 |
-
# # Helps with validation PPL, since the val
|
| 193 |
-
# # examples will all start and end with BOS/EOS
|
| 194 |
-
# input_tokens[:, 0] = self.tokenizer.bos_token_id
|
| 195 |
-
# output_tokens[:, -1] = self.tokenizer.eos_token_id
|
| 196 |
-
|
| 197 |
-
# elif self.parameterization == 'ar':
|
| 198 |
-
# input_tokens = x0[:, :-1]
|
| 199 |
-
# output_tokens = x0[:, 1:]
|
| 200 |
-
# new_attention_mask = attention_mask[:, 1:]
|
| 201 |
-
# else:
|
| 202 |
-
input_tokens = x0
|
| 203 |
-
output_tokens = None
|
| 204 |
-
new_attention_mask = attention_mask
|
| 205 |
-
|
| 206 |
-
return input_tokens, output_tokens, new_attention_mask
|
| 207 |
-
|
| 208 |
-
def compute_loss(self, latents, attention_mask):
|
| 209 |
-
""""Average of MLM losses to stabilize training"""
|
| 210 |
-
(input_tokens, output_tokens, attention_mask) = self.maybe_sub_sample(latents, attention_mask)
|
| 211 |
-
loss = self.forward_diffusion(input_tokens)
|
| 212 |
-
|
| 213 |
-
nlls = loss * attention_mask
|
| 214 |
-
count = attention_mask.sum()
|
| 215 |
-
batch_nll = nlls.sum()
|
| 216 |
-
token_nll = batch_nll / count
|
| 217 |
-
|
| 218 |
-
return Loss(loss=token_nll, nlls=nlls, token_mask=attention_mask)
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
######### TRAINING #########
|
| 222 |
-
def training_step(self, batch, batch_idx):
|
| 223 |
-
latents, attention_mask = batch
|
| 224 |
-
loss = self.compute_loss(latents, attention_mask)
|
| 225 |
-
return loss
|
| 226 |
-
|
| 227 |
-
def configure_optimizers(self):
|
| 228 |
-
optimizer = torch.optim.Adam(self.parameters(), lr=self.lr)
|
| 229 |
-
return optimizer
|
| 230 |
-
|
| 231 |
-
def validation_step(self, batch):
|
| 232 |
-
latents, attention_mask = batch
|
| 233 |
-
loss = self.compute_loss(latents, attention_mask)
|
| 234 |
-
return loss
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
######### GENERATION #########
|
| 238 |
-
def sample_prior(self, *batch_dims):
|
| 239 |
-
return self.mask_index * torch.ones(* batch_dims, dtype=torch.int64)
|
| 240 |
-
|
| 241 |
-
def sample_categorical(categorical_probs):
|
| 242 |
-
gumbel_norm = (1e-10 - (torch.rand_like(categorical_probs) + 1e-10).log())
|
| 243 |
-
return (categorical_probs / gumbel_norm).argmax(dim=-1)
|
| 244 |
-
|
| 245 |
-
def ddpm_caching_update(self, x, t, dt, p_x0=None):
|
| 246 |
-
assert self.config.noise.type == 'loglinear'
|
| 247 |
-
sigma_t, _ = self.noise(t)
|
| 248 |
-
if t.ndim > 1:
|
| 249 |
-
t = t.squeeze(-1)
|
| 250 |
-
assert t.ndim == 1
|
| 251 |
-
move_chance_t = t[:, None, None]
|
| 252 |
-
move_chance_s = (t - dt)[:, None, None]
|
| 253 |
-
assert move_chance_t.ndim == 3, move_chance_t.shape
|
| 254 |
-
if p_x0 is None:
|
| 255 |
-
p_x0 = self.forward(x, sigma_t).exp()
|
| 256 |
-
|
| 257 |
-
assert move_chance_t.ndim == p_x0.ndim
|
| 258 |
-
q_xs = p_x0 * (move_chance_t - move_chance_s)
|
| 259 |
-
q_xs[:, :, self.mask_index] = move_chance_s[:, :, 0]
|
| 260 |
-
_x = self.sample_categorical(q_xs)
|
| 261 |
-
|
| 262 |
-
copy_flag = (x != self.mask_index).to(x.dtype)
|
| 263 |
-
return p_x0, copy_flag * x + (1 - copy_flag) * _x
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
@torch.no_grad()
|
| 267 |
-
def sample_subs_guidance(self, n_samples, stride_length, num_strides, dt=0.001):
|
| 268 |
-
ones = torch.ones(n_samples, dtype=self.dtype,device=self.device)
|
| 269 |
-
num_steps = int(1 / dt)
|
| 270 |
-
sampling_steps = 0
|
| 271 |
-
intermediate_tokens = []
|
| 272 |
-
target = None
|
| 273 |
-
|
| 274 |
-
for _ in range(num_strides + 1):
|
| 275 |
-
p_x0_cache = None
|
| 276 |
-
x = self._sample_prior(n_samples,self.config.model.length).to(self.device)
|
| 277 |
-
|
| 278 |
-
if target is not None:
|
| 279 |
-
x[:, : -stride_length] = target
|
| 280 |
-
|
| 281 |
-
for i in range(num_steps + 1):
|
| 282 |
-
p_x0_cache, x_next = self.ddpm_caching_update(x=x, t=(1 - i * dt) * ones, dt=dt, p_x0=p_x0_cache)
|
| 283 |
-
if (not torch.allclose(x_next, x) or self.time_conditioning):
|
| 284 |
-
p_x0_cache = None
|
| 285 |
-
sampling_steps += 1
|
| 286 |
-
x = x_next
|
| 287 |
-
x = self.forward(x, 0 * ones).argmax(dim=-1)
|
| 288 |
-
intermediate_tokens.append(x[:, :stride_length].cpu().numpy())
|
| 289 |
-
target = x[:, stride_length:]
|
| 290 |
-
|
| 291 |
-
intermediate_tokens.append(target.cpu().numpy())
|
| 292 |
-
intermediate_text_samples = []
|
| 293 |
-
sequence_lengths = ((np.concatenate(intermediate_tokens, axis=1)[:, 1:]
|
| 294 |
-
== self.tokenizer.eos_token_id).cumsum(-1) == 0).sum(-1)
|
| 295 |
-
|
| 296 |
-
for i in range(2, len(intermediate_tokens) + 1):
|
| 297 |
-
intermediate_text_samples.append(self.tokenizer.decode(np.concatenate(intermediate_tokens[:i], axis=1)))
|
| 298 |
-
|
| 299 |
-
return (sampling_steps, intermediate_text_samples,
|
| 300 |
-
sequence_lengths)
|
| 301 |
-
|
| 302 |
-
def restore_model_and_semi_ar_sample(self, stride_length, num_strides, dt=0.001):
|
| 303 |
-
"""Generate samples from the model."""
|
| 304 |
-
# Lightning auto-casting is not working in this method for some reason
|
| 305 |
-
self.backbone.eval()
|
| 306 |
-
self.noise.eval()
|
| 307 |
-
|
| 308 |
-
(sampling_steps, samples, sequence_lengths) = self.sample_subs_guidance(n_samples=self.config.Loader.BATCH_SIZE,stride_length=stride_length,num_strides=num_strides,dt=dt)
|
| 309 |
-
|
| 310 |
-
self.backbone.train()
|
| 311 |
-
self.noise.train()
|
| 312 |
-
return sampling_steps, samples, sequence_lengths
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
models/dit.py
DELETED
|
@@ -1,369 +0,0 @@
|
|
| 1 |
-
import math
|
| 2 |
-
import typing
|
| 3 |
-
|
| 4 |
-
import flash_attn
|
| 5 |
-
import flash_attn.layers.rotary
|
| 6 |
-
import huggingface_hub
|
| 7 |
-
import omegaconf
|
| 8 |
-
import torch
|
| 9 |
-
import torch.nn as nn
|
| 10 |
-
import torch.nn.functional as F
|
| 11 |
-
from einops import rearrange
|
| 12 |
-
|
| 13 |
-
# Flags required to enable jit fusion kernels
|
| 14 |
-
torch._C._jit_set_profiling_mode(False)
|
| 15 |
-
torch._C._jit_set_profiling_executor(False)
|
| 16 |
-
torch._C._jit_override_can_fuse_on_cpu(True)
|
| 17 |
-
torch._C._jit_override_can_fuse_on_gpu(True)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def bias_dropout_add_scale(
|
| 21 |
-
x: torch.Tensor,
|
| 22 |
-
bias: typing.Optional[torch.Tensor],
|
| 23 |
-
scale: torch.Tensor,
|
| 24 |
-
residual: typing.Optional[torch.Tensor],
|
| 25 |
-
prob: float,
|
| 26 |
-
training: bool) -> torch.Tensor:
|
| 27 |
-
if bias is not None:
|
| 28 |
-
out = scale * F.dropout(x + bias, p=prob, training=training)
|
| 29 |
-
else:
|
| 30 |
-
out = scale * F.dropout(x, p=prob, training=training)
|
| 31 |
-
|
| 32 |
-
if residual is not None:
|
| 33 |
-
out = residual + out
|
| 34 |
-
return out
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def get_bias_dropout_add_scale(training):
|
| 38 |
-
def _bias_dropout_add(x, bias, scale, residual, prob):
|
| 39 |
-
return bias_dropout_add_scale(
|
| 40 |
-
x, bias, scale, residual, prob, training)
|
| 41 |
-
|
| 42 |
-
return _bias_dropout_add
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
# function overload
|
| 46 |
-
def modulate(x: torch.Tensor,
|
| 47 |
-
shift: torch.Tensor,
|
| 48 |
-
scale: torch.Tensor) -> torch.Tensor:
|
| 49 |
-
return x * (1 + scale) + shift
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
@torch.jit.script
|
| 53 |
-
def bias_dropout_add_scale_fused_train(
|
| 54 |
-
x: torch.Tensor,
|
| 55 |
-
bias: typing.Optional[torch.Tensor],
|
| 56 |
-
scale: torch.Tensor,
|
| 57 |
-
residual: typing.Optional[torch.Tensor],
|
| 58 |
-
prob: float) -> torch.Tensor:
|
| 59 |
-
return bias_dropout_add_scale(
|
| 60 |
-
x, bias, scale, residual, prob, True)
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
@torch.jit.script
|
| 64 |
-
def bias_dropout_add_scale_fused_inference(
|
| 65 |
-
x: torch.Tensor,
|
| 66 |
-
bias: typing.Optional[torch.Tensor],
|
| 67 |
-
scale: torch.Tensor,
|
| 68 |
-
residual: typing.Optional[torch.Tensor],
|
| 69 |
-
prob: float) -> torch.Tensor:
|
| 70 |
-
return bias_dropout_add_scale(
|
| 71 |
-
x, bias, scale, residual, prob, False)
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
@torch.jit.script
|
| 75 |
-
def modulate_fused(x: torch.Tensor,
|
| 76 |
-
shift: torch.Tensor,
|
| 77 |
-
scale: torch.Tensor) -> torch.Tensor:
|
| 78 |
-
return modulate(x, shift, scale)
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
class Rotary(torch.nn.Module):
|
| 82 |
-
def __init__(self, dim, base=10_000):
|
| 83 |
-
super().__init__()
|
| 84 |
-
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
| 85 |
-
self.register_buffer('inv_freq', inv_freq)
|
| 86 |
-
self.seq_len_cached = None
|
| 87 |
-
self.cos_cached = None
|
| 88 |
-
self.sin_cached = None
|
| 89 |
-
|
| 90 |
-
def forward(self, x, seq_dim=1):
|
| 91 |
-
seq_len = x.shape[seq_dim]
|
| 92 |
-
if seq_len != self.seq_len_cached:
|
| 93 |
-
self.seq_len_cached = seq_len
|
| 94 |
-
t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq)
|
| 95 |
-
freqs = torch.einsum("i,j->ij", t, self.inv_freq.clone())
|
| 96 |
-
emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
|
| 97 |
-
# dims are: batch, seq_len, qkv, head, dim
|
| 98 |
-
self.cos_cached = emb.cos()[None, :, None, None, :].repeat(1,1,3,1,1)
|
| 99 |
-
self.sin_cached = emb.sin()[None, :, None, None, :].repeat(1,1,3,1,1)
|
| 100 |
-
# This makes the transformation on v an identity.
|
| 101 |
-
self.cos_cached[:,:,2,:,:].fill_(1.)
|
| 102 |
-
self.sin_cached[:,:,2,:,:].fill_(0.)
|
| 103 |
-
|
| 104 |
-
return self.cos_cached, self.sin_cached
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
def rotate_half(x):
|
| 108 |
-
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
|
| 109 |
-
return torch.cat((-x2, x1), dim=-1)
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
def apply_rotary_pos_emb(qkv, cos, sin):
|
| 113 |
-
cos = cos[0,:,0,0,:cos.shape[-1]//2]
|
| 114 |
-
sin = sin[0,:,0,0,:sin.shape[-1]//2]
|
| 115 |
-
return flash_attn.layers.rotary.apply_rotary_emb_qkv_(qkv, cos, sin)
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
# function overload
|
| 119 |
-
def modulate(x, shift, scale):
|
| 120 |
-
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
#################################################################################
|
| 124 |
-
# Layers #
|
| 125 |
-
#################################################################################
|
| 126 |
-
class LayerNorm(nn.Module):
|
| 127 |
-
def __init__(self, dim):
|
| 128 |
-
super().__init__()
|
| 129 |
-
self.weight = nn.Parameter(torch.ones([dim]))
|
| 130 |
-
self.dim = dim
|
| 131 |
-
def forward(self, x):
|
| 132 |
-
with torch.cuda.amp.autocast(enabled=False):
|
| 133 |
-
x = F.layer_norm(x.float(), [self.dim])
|
| 134 |
-
return x * self.weight[None,None,:]
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
def residual_linear(x, W, x_skip, residual_scale):
|
| 138 |
-
"""x_skip + residual_scale * W @ x"""
|
| 139 |
-
dim_out, dim_in = W.shape[0], W.shape[1]
|
| 140 |
-
return torch.addmm(
|
| 141 |
-
x_skip.view(-1, dim_out),
|
| 142 |
-
x.view(-1, dim_in),
|
| 143 |
-
W.T,
|
| 144 |
-
alpha=residual_scale).view(*x.shape[:-1], dim_out)
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
#################################################################################
|
| 148 |
-
# Embedding Layers for Timesteps and Class Labels #
|
| 149 |
-
#################################################################################
|
| 150 |
-
class TimestepEmbedder(nn.Module):
|
| 151 |
-
"""
|
| 152 |
-
Embeds scalar timesteps into vector representations.
|
| 153 |
-
"""
|
| 154 |
-
def __init__(self, hidden_size, frequency_embedding_size=256):
|
| 155 |
-
super().__init__()
|
| 156 |
-
self.mlp = nn.Sequential(
|
| 157 |
-
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
|
| 158 |
-
nn.SiLU(),
|
| 159 |
-
nn.Linear(hidden_size, hidden_size, bias=True))
|
| 160 |
-
self.frequency_embedding_size = frequency_embedding_size
|
| 161 |
-
|
| 162 |
-
@staticmethod
|
| 163 |
-
def timestep_embedding(t, dim, max_period=10000):
|
| 164 |
-
"""
|
| 165 |
-
Create sinusoidal timestep embeddings.
|
| 166 |
-
:param t: a 1-D Tensor of N indices, one per batch element.
|
| 167 |
-
These may be fractional.
|
| 168 |
-
:param dim: the dimension of the output.
|
| 169 |
-
:param max_period: controls the minimum frequency of the embeddings.
|
| 170 |
-
:return: an (N, D) Tensor of positional embeddings.
|
| 171 |
-
"""
|
| 172 |
-
# https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
|
| 173 |
-
half = dim // 2
|
| 174 |
-
freqs = torch.exp(
|
| 175 |
-
- math.log(max_period)
|
| 176 |
-
* torch.arange(start=0, end=half, dtype=torch.float32)
|
| 177 |
-
/ half).to(device=t.device)
|
| 178 |
-
args = t[:, None].float() * freqs[None]
|
| 179 |
-
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 180 |
-
if dim % 2:
|
| 181 |
-
embedding = torch.cat(
|
| 182 |
-
[embedding,
|
| 183 |
-
torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 184 |
-
return embedding
|
| 185 |
-
|
| 186 |
-
def forward(self, t):
|
| 187 |
-
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
|
| 188 |
-
t_emb = self.mlp(t_freq)
|
| 189 |
-
return t_emb
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
class LabelEmbedder(nn.Module):
|
| 193 |
-
"""Embeds class labels into vector representations.
|
| 194 |
-
|
| 195 |
-
Also handles label dropout for classifier-free guidance.
|
| 196 |
-
"""
|
| 197 |
-
def __init__(self, num_classes, cond_size):
|
| 198 |
-
super().__init__()
|
| 199 |
-
self.embedding_table = nn.Embedding(num_classes + 1, cond_size)
|
| 200 |
-
self.num_classes = num_classes
|
| 201 |
-
|
| 202 |
-
# TODO think of initializing with 0.02 std deviation like in original DiT paper
|
| 203 |
-
|
| 204 |
-
def forward(self, labels):
|
| 205 |
-
embeddings = self.embedding_table(labels)
|
| 206 |
-
return embeddings
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
#################################################################################
|
| 210 |
-
# Core Model #
|
| 211 |
-
#################################################################################
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
class DDiTBlock(nn.Module):
|
| 215 |
-
def __init__(self, dim, n_heads, cond_dim, mlp_ratio=4, dropout=0.1):
|
| 216 |
-
super().__init__()
|
| 217 |
-
self.n_heads = n_heads
|
| 218 |
-
|
| 219 |
-
self.norm1 = LayerNorm(dim)
|
| 220 |
-
self.attn_qkv = nn.Linear(dim, 3 * dim, bias=False)
|
| 221 |
-
self.attn_out = nn.Linear(dim, dim, bias=False)
|
| 222 |
-
self.dropout1 = nn.Dropout(dropout)
|
| 223 |
-
|
| 224 |
-
self.norm2 = LayerNorm(dim)
|
| 225 |
-
self.mlp = nn.Sequential(
|
| 226 |
-
nn.Linear(dim, mlp_ratio * dim, bias=True),
|
| 227 |
-
nn.GELU(approximate='tanh'),
|
| 228 |
-
nn.Linear(mlp_ratio * dim, dim, bias=True))
|
| 229 |
-
self.dropout2 = nn.Dropout(dropout)
|
| 230 |
-
self.dropout = dropout
|
| 231 |
-
|
| 232 |
-
self.adaLN_modulation = nn.Linear(cond_dim, 6 * dim, bias=True)
|
| 233 |
-
self.adaLN_modulation.weight.data.zero_()
|
| 234 |
-
self.adaLN_modulation.bias.data.zero_()
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
def _get_bias_dropout_scale(self):
|
| 238 |
-
if self.training:
|
| 239 |
-
return bias_dropout_add_scale_fused_train
|
| 240 |
-
else:
|
| 241 |
-
return bias_dropout_add_scale_fused_inference
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
def forward(self, x, rotary_cos_sin, c, seqlens=None):
|
| 245 |
-
batch_size, seq_len = x.shape[0], x.shape[1]
|
| 246 |
-
|
| 247 |
-
bias_dropout_scale_fn = self._get_bias_dropout_scale()
|
| 248 |
-
|
| 249 |
-
(shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp) = self.adaLN_modulation(c)[:, None][0].chunk(6, dim=2)
|
| 250 |
-
|
| 251 |
-
# attention operation
|
| 252 |
-
x_skip = x
|
| 253 |
-
x = modulate_fused(self.norm1(x), shift_msa, scale_msa)
|
| 254 |
-
|
| 255 |
-
qkv = self.attn_qkv(x)
|
| 256 |
-
qkv = rearrange(qkv,
|
| 257 |
-
'b s (three h d) -> b s three h d',
|
| 258 |
-
three=3,
|
| 259 |
-
h=self.n_heads)
|
| 260 |
-
with torch.cuda.amp.autocast(enabled=False):
|
| 261 |
-
cos, sin = rotary_cos_sin
|
| 262 |
-
qkv = apply_rotary_pos_emb(
|
| 263 |
-
qkv, cos.to(qkv.dtype), sin.to(qkv.dtype))
|
| 264 |
-
qkv = rearrange(qkv, 'b s ... -> (b s) ...')
|
| 265 |
-
if seqlens is None:
|
| 266 |
-
cu_seqlens = torch.arange(
|
| 267 |
-
0, (batch_size + 1) * seq_len, step=seq_len,
|
| 268 |
-
dtype=torch.int32, device=qkv.device)
|
| 269 |
-
else:
|
| 270 |
-
cu_seqlens = seqlens.cumsum(-1)
|
| 271 |
-
x = flash_attn.flash_attn_interface.flash_attn_varlen_qkvpacked_func(
|
| 272 |
-
qkv, cu_seqlens, seq_len, 0., causal=False)
|
| 273 |
-
|
| 274 |
-
x = rearrange(x, '(b s) h d -> b s (h d)', b=batch_size)
|
| 275 |
-
|
| 276 |
-
x = bias_dropout_scale_fn(self.attn_out(x),
|
| 277 |
-
None,
|
| 278 |
-
gate_msa,
|
| 279 |
-
x_skip,
|
| 280 |
-
self.dropout)
|
| 281 |
-
|
| 282 |
-
# mlp operation
|
| 283 |
-
x = bias_dropout_scale_fn(
|
| 284 |
-
self.mlp(modulate_fused(
|
| 285 |
-
self.norm2(x), shift_mlp, scale_mlp)),
|
| 286 |
-
None, gate_mlp, x, self.dropout)
|
| 287 |
-
return x
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
class EmbeddingLayer(nn.Module):
|
| 292 |
-
def __init__(self, dim, vocab_dim):
|
| 293 |
-
super().__init__()
|
| 294 |
-
self.embedding = nn.Parameter(torch.empty((vocab_dim, dim)))
|
| 295 |
-
torch.nn.init.kaiming_uniform_(self.embedding, a=math.sqrt(5))
|
| 296 |
-
|
| 297 |
-
def forward(self, x):
|
| 298 |
-
return self.embedding[x]
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
class DDitFinalLayer(nn.Module):
|
| 302 |
-
def __init__(self, hidden_size, out_channels, cond_dim):
|
| 303 |
-
super().__init__()
|
| 304 |
-
self.norm_final = LayerNorm(hidden_size)
|
| 305 |
-
self.linear = nn.Linear(hidden_size, out_channels)
|
| 306 |
-
self.linear.weight.data.zero_()
|
| 307 |
-
self.linear.bias.data.zero_()
|
| 308 |
-
|
| 309 |
-
self.adaLN_modulation = nn.Linear(cond_dim,
|
| 310 |
-
2 * hidden_size,
|
| 311 |
-
bias=True)
|
| 312 |
-
self.adaLN_modulation.weight.data.zero_()
|
| 313 |
-
self.adaLN_modulation.bias.data.zero_()
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
def forward(self, x, c):
|
| 317 |
-
shift, scale = self.adaLN_modulation(c)[:, None][0].chunk(2, dim=2)
|
| 318 |
-
x = modulate_fused(self.norm_final(x), shift, scale)
|
| 319 |
-
x = self.linear(x)
|
| 320 |
-
return x
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
class DIT(nn.Module, huggingface_hub.PyTorchModelHubMixin):
|
| 324 |
-
def __init__(self, config, vocab_size: int):
|
| 325 |
-
super().__init__()
|
| 326 |
-
if type(config) == dict:
|
| 327 |
-
config = omegaconf.OmegaConf.create(config)
|
| 328 |
-
|
| 329 |
-
self.config = config
|
| 330 |
-
self.vocab_size = vocab_size
|
| 331 |
-
|
| 332 |
-
self.vocab_embed = EmbeddingLayer(config.model.hidden_size,
|
| 333 |
-
vocab_size)
|
| 334 |
-
self.sigma_map = TimestepEmbedder(config.model.cond_dim)
|
| 335 |
-
self.rotary_emb = Rotary(
|
| 336 |
-
config.model.hidden_size // config.model.n_heads)
|
| 337 |
-
|
| 338 |
-
blocks = []
|
| 339 |
-
for _ in range(config.model.n_blocks):
|
| 340 |
-
blocks.append(DDiTBlock(config.model.hidden_size,
|
| 341 |
-
config.model.n_heads,
|
| 342 |
-
config.model.cond_dim,
|
| 343 |
-
dropout=config.model.dropout))
|
| 344 |
-
self.blocks = nn.ModuleList(blocks)
|
| 345 |
-
|
| 346 |
-
self.output_layer = DDitFinalLayer(
|
| 347 |
-
config.model.hidden_size,
|
| 348 |
-
vocab_size,
|
| 349 |
-
config.model.cond_dim)
|
| 350 |
-
#self.scale_by_sigma = config.model.scale_by_sigma
|
| 351 |
-
|
| 352 |
-
def _get_bias_dropout_scale(self):
|
| 353 |
-
if self.training:
|
| 354 |
-
return bias_dropout_add_scale_fused_train
|
| 355 |
-
else:
|
| 356 |
-
return bias_dropout_add_scale_fused_inference
|
| 357 |
-
|
| 358 |
-
def forward(self, indices, sigma):
|
| 359 |
-
x = self.vocab_embed(indices)
|
| 360 |
-
c = F.silu(self.sigma_map(sigma))
|
| 361 |
-
|
| 362 |
-
rotary_cos_sin = self.rotary_emb(x)
|
| 363 |
-
|
| 364 |
-
with torch.cuda.amp.autocast(dtype=torch.bfloat16):
|
| 365 |
-
for i in range(len(self.blocks)):
|
| 366 |
-
x = self.blocks[i](x, rotary_cos_sin, c, seqlens=None)
|
| 367 |
-
x = self.output_layer(x, c)
|
| 368 |
-
|
| 369 |
-
return x
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
models/ema.py
DELETED
|
@@ -1,97 +0,0 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
class ExponentialMovingAverage:
|
| 5 |
-
"""
|
| 6 |
-
Maintains (exponential) moving average of a set of parameters.
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
def __init__(self, parameters, decay, use_num_updates=True):
|
| 10 |
-
"""
|
| 11 |
-
Args:
|
| 12 |
-
parameters: Iterable of `torch.nn.Parameter`; usually the result of
|
| 13 |
-
`model.parameters()`.
|
| 14 |
-
decay: The exponential decay.
|
| 15 |
-
use_num_updates: Whether to use number of updates when computing
|
| 16 |
-
averages.
|
| 17 |
-
"""
|
| 18 |
-
if decay < 0.0 or decay > 1.0:
|
| 19 |
-
raise ValueError('Decay must be between 0 and 1')
|
| 20 |
-
self.decay = decay
|
| 21 |
-
self.num_updates = 0 if use_num_updates else None
|
| 22 |
-
self.shadow_params = [p.clone().detach()
|
| 23 |
-
for p in parameters if p.requires_grad]
|
| 24 |
-
self.collected_params = []
|
| 25 |
-
|
| 26 |
-
def move_shadow_params_to_device(self, device):
|
| 27 |
-
self.shadow_params = [i.to(device) for i in self.shadow_params]
|
| 28 |
-
|
| 29 |
-
def update(self, parameters):
|
| 30 |
-
"""
|
| 31 |
-
Update currently maintained parameters.
|
| 32 |
-
|
| 33 |
-
Call this every time the parameters are updated, such as the result of
|
| 34 |
-
the `optimizer.step()` call.
|
| 35 |
-
|
| 36 |
-
Args:
|
| 37 |
-
parameters: Iterable of `torch.nn.Parameter`; usually the same set of
|
| 38 |
-
parameters used to initialize this object.
|
| 39 |
-
"""
|
| 40 |
-
decay = self.decay
|
| 41 |
-
if self.num_updates is not None:
|
| 42 |
-
self.num_updates += 1
|
| 43 |
-
decay = min(decay, (1 + self.num_updates) /
|
| 44 |
-
(10 + self.num_updates))
|
| 45 |
-
one_minus_decay = 1.0 - decay
|
| 46 |
-
with torch.no_grad():
|
| 47 |
-
parameters = [p for p in parameters if p.requires_grad]
|
| 48 |
-
for s_param, param in zip(self.shadow_params, parameters):
|
| 49 |
-
s_param.sub_(one_minus_decay * (s_param - param))
|
| 50 |
-
|
| 51 |
-
def copy_to(self, parameters):
|
| 52 |
-
"""
|
| 53 |
-
Copy current parameters into given collection of parameters.
|
| 54 |
-
|
| 55 |
-
Args:
|
| 56 |
-
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
| 57 |
-
updated with the stored moving averages.
|
| 58 |
-
"""
|
| 59 |
-
parameters = [p for p in parameters if p.requires_grad]
|
| 60 |
-
for s_param, param in zip(self.shadow_params, parameters):
|
| 61 |
-
if param.requires_grad:
|
| 62 |
-
param.data.copy_(s_param.data)
|
| 63 |
-
|
| 64 |
-
def store(self, parameters):
|
| 65 |
-
"""
|
| 66 |
-
Save the current parameters for restoring later.
|
| 67 |
-
|
| 68 |
-
Args:
|
| 69 |
-
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
| 70 |
-
temporarily stored.
|
| 71 |
-
"""
|
| 72 |
-
self.collected_params = [param.clone() for param in parameters]
|
| 73 |
-
|
| 74 |
-
def restore(self, parameters):
|
| 75 |
-
"""
|
| 76 |
-
Restore the parameters stored with the `store` method.
|
| 77 |
-
Useful to validate the model with EMA parameters without affecting the
|
| 78 |
-
original optimization process. Store the parameters before the
|
| 79 |
-
`copy_to` method. After validation (or model saving), use this to
|
| 80 |
-
restore the former parameters.
|
| 81 |
-
|
| 82 |
-
Args:
|
| 83 |
-
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
| 84 |
-
updated with the stored parameters.
|
| 85 |
-
"""
|
| 86 |
-
for c_param, param in zip(self.collected_params, parameters):
|
| 87 |
-
param.data.copy_(c_param.data)
|
| 88 |
-
|
| 89 |
-
def state_dict(self):
|
| 90 |
-
return dict(decay=self.decay,
|
| 91 |
-
num_updates=self.num_updates,
|
| 92 |
-
shadow_params=self.shadow_params)
|
| 93 |
-
|
| 94 |
-
def load_state_dict(self, state_dict):
|
| 95 |
-
self.decay = state_dict['decay']
|
| 96 |
-
self.num_updates = state_dict['num_updates']
|
| 97 |
-
self.shadow_params = state_dict['shadow_params']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|