| 160 | "num_groups":16, "st_norm_eps":1e-6} |
| 161 | |
| 162 | class StableDiffusion: |
| 163 | def __init__(self, version:str|None=None, pretrained:str|None=None): |
| 164 | self.alphas_cumprod = get_alphas_cumprod() |
| 165 | if version != "v2-mlperf-train": |
| 166 | self.first_stage_model = AutoencoderKL() # only needed for decoding generated latents to images; not needed in mlperf training from preprocessed moments |
| 167 | |
| 168 | if not version: |
| 169 | self.cond_stage_model = namedtuple("CondStageModel", ["transformer"])(transformer = namedtuple("Transformer", ["text_model"])(text_model = Closed.ClipTextTransformer())) |
| 170 | unet_init_params = unet_params |
| 171 | elif version in {"v2-mlperf-train", "v2-mlperf-eval"}: |
| 172 | unet_init_params = mlperf_params |
| 173 | clip.gelu = gelu_erf |
| 174 | self.cond_stage_model = FrozenOpenClipEmbedder(**{"dims": 1024, "n_heads": 16, "layers": 24, "return_pooled": False, "ln_penultimate": True, |
| 175 | "clip_tokenizer_version": "sd_mlperf_v5_0"}) |
| 176 | unet.Linear, unet.Conv2d, unet.GroupNorm, unet.LayerNorm = AutocastLinear, AutocastConv2d, AutocastGroupNorm, AutocastLayerNorm |
| 177 | unet.attention, unet.gelu, unet.mixed_precision_dtype = attn_f32_softmax, gelu_erf, dtypes.bfloat16 |
| 178 | if pretrained: |
| 179 | print("loading text encoder") |
| 180 | weights: dict[str,Tensor] = {k.replace("cond_stage_model.", "", 1):v for k,v in torch_load(pretrained)["state_dict"].items() if k.startswith("cond_stage_model.")} |
| 181 | weights["model.attn_mask"] = Tensor.full((77, 77), fill_value=float("-inf")).triu(1) |
| 182 | load_state_dict(self.cond_stage_model, weights) |
| 183 | # only the eval model needs the decoder |
| 184 | if version == "v2-mlperf-eval": |
| 185 | print("loading image latent encoder") |
| 186 | weights = {k.replace("first_stage_model.", "", 1):v for k,v in torch_load(pretrained)["state_dict"].items() if k.startswith("first_stage_model.")} |
| 187 | load_state_dict(self.first_stage_model, weights) |
| 188 | |
| 189 | self.model = namedtuple("DiffusionModel", ["diffusion_model"])(diffusion_model = UNetModel(**unet_init_params)) |
| 190 | if version == "v2-mlperf-train": |
| 191 | # the mlperf reference inits certain weights as zeroes |
| 192 | for bb in flatten(self.model.diffusion_model.input_blocks) + self.model.diffusion_model.middle_block + flatten(self.model.diffusion_model.output_blocks): |
| 193 | if isinstance(bb, unet.ResBlock): |
| 194 | zero_module(bb.out_layers[3]) |
| 195 | elif isinstance(bb, unet.SpatialTransformer): |
| 196 | zero_module(bb.proj_out) |
| 197 | zero_module(self.model.diffusion_model.out[2]) |
| 198 | |
| 199 | def get_x_prev_and_pred_x0(self, x, e_t, a_t, a_prev): |
| 200 | temperature = 1 |
| 201 | sigma_t = 0 |
| 202 | sqrt_one_minus_at = (1-a_t).sqrt() |
| 203 | #print(a_t, a_prev, sigma_t, sqrt_one_minus_at) |
| 204 | |
| 205 | pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() |
| 206 | |
| 207 | # direction pointing to x_t |
| 208 | dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t |
| 209 | |
| 210 | x_prev = a_prev.sqrt() * pred_x0 + dir_xt |
| 211 | return x_prev, pred_x0 |
| 212 | |
| 213 | def get_model_output(self, unconditional_context, context, latent, timestep, unconditional_guidance_scale): |
| 214 | # put into diffuser |
| 215 | latents = self.model.diffusion_model(latent.expand(2, *latent.shape[1:]), timestep, unconditional_context.cat(context, dim=0)) |
| 216 | unconditional_latent, latent = latents[0:1], latents[1:2] |
| 217 | |
| 218 | e_t = unconditional_latent + unconditional_guidance_scale * (latent - unconditional_latent) |
| 219 | return e_t |
no outgoing calls
no test coverage detected
searching dependent graphs…