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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gc
|
| 2 |
+
import os, sys
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
import numpy as np
|
| 5 |
+
import json
|
| 6 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 7 |
+
|
| 8 |
+
# set visible devices to 0
|
| 9 |
+
# os.environ["CUDA_VISIBLE_DEVICES"] = "0"
|
| 10 |
+
|
| 11 |
+
# protect from formatting
|
| 12 |
+
if True:
|
| 13 |
+
import torch
|
| 14 |
+
from optimum.quanto import freeze, qfloat8, QTensor, qint4
|
| 15 |
+
from diffusers import FluxTransformer2DModel, FluxPipeline, AutoencoderKL, FlowMatchEulerDiscreteScheduler
|
| 16 |
+
from toolkit.util.quantize import quantize, get_qtype
|
| 17 |
+
from transformers import T5EncoderModel, T5TokenizerFast, CLIPTextModel, CLIPTokenizer
|
| 18 |
+
from torchvision import transforms
|
| 19 |
+
|
| 20 |
+
qtype = "qfloat8"
|
| 21 |
+
dtype = torch.bfloat16
|
| 22 |
+
# base_model_path = "black-forest-labs/FLUX.1-dev"
|
| 23 |
+
base_model_path = "ostris/Flex.1-alpha"
|
| 24 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 25 |
+
print("Loading Transformer...")
|
| 26 |
+
prompt = "Photo of a man and a woman in a park, sunny day"
|
| 27 |
+
|
| 28 |
+
output_root = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "output")
|
| 29 |
+
output_path = os.path.join(output_root, "flex_timestep_weights.json")
|
| 30 |
+
img_output_path = os.path.join(output_root, "flex_timestep_weights.png")
|
| 31 |
+
|
| 32 |
+
quantization_type = get_qtype(qtype)
|
| 33 |
+
|
| 34 |
+
def flush():
|
| 35 |
+
torch.cuda.empty_cache()
|
| 36 |
+
gc.collect()
|
| 37 |
+
|
| 38 |
+
pil_to_tensor = transforms.ToTensor()
|
| 39 |
+
|
| 40 |
+
with torch.no_grad():
|
| 41 |
+
transformer = FluxTransformer2DModel.from_pretrained(
|
| 42 |
+
base_model_path,
|
| 43 |
+
subfolder='transformer',
|
| 44 |
+
torch_dtype=dtype
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
transformer.to(device, dtype=dtype)
|
| 48 |
+
|
| 49 |
+
print("Quantizing Transformer...")
|
| 50 |
+
quantize(transformer, weights=quantization_type)
|
| 51 |
+
freeze(transformer)
|
| 52 |
+
flush()
|
| 53 |
+
|
| 54 |
+
print("Loading Scheduler...")
|
| 55 |
+
scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(base_model_path, subfolder="scheduler")
|
| 56 |
+
|
| 57 |
+
print("Loading Autoencoder...")
|
| 58 |
+
vae = AutoencoderKL.from_pretrained(base_model_path, subfolder="vae", torch_dtype=dtype)
|
| 59 |
+
|
| 60 |
+
vae.to(device, dtype=dtype)
|
| 61 |
+
|
| 62 |
+
flush()
|
| 63 |
+
print("Loading Text Encoder...")
|
| 64 |
+
tokenizer_2 = T5TokenizerFast.from_pretrained(base_model_path, subfolder="tokenizer_2", torch_dtype=dtype)
|
| 65 |
+
text_encoder_2 = T5EncoderModel.from_pretrained(base_model_path, subfolder="text_encoder_2", torch_dtype=dtype)
|
| 66 |
+
text_encoder_2.to(device, dtype=dtype)
|
| 67 |
+
|
| 68 |
+
print("Quantizing Text Encoder...")
|
| 69 |
+
quantize(text_encoder_2, weights=get_qtype(qtype))
|
| 70 |
+
freeze(text_encoder_2)
|
| 71 |
+
flush()
|
| 72 |
+
|
| 73 |
+
print("Loading CLIP")
|
| 74 |
+
text_encoder = CLIPTextModel.from_pretrained(base_model_path, subfolder="text_encoder", torch_dtype=dtype)
|
| 75 |
+
tokenizer = CLIPTokenizer.from_pretrained(base_model_path, subfolder="tokenizer", torch_dtype=dtype)
|
| 76 |
+
text_encoder.to(device, dtype=dtype)
|
| 77 |
+
|
| 78 |
+
print("Making pipe")
|
| 79 |
+
|
| 80 |
+
pipe: FluxPipeline = FluxPipeline(
|
| 81 |
+
scheduler=scheduler,
|
| 82 |
+
text_encoder=text_encoder,
|
| 83 |
+
tokenizer=tokenizer,
|
| 84 |
+
text_encoder_2=None,
|
| 85 |
+
tokenizer_2=tokenizer_2,
|
| 86 |
+
vae=vae,
|
| 87 |
+
transformer=None,
|
| 88 |
+
)
|
| 89 |
+
pipe.text_encoder_2 = text_encoder_2
|
| 90 |
+
pipe.transformer = transformer
|
| 91 |
+
|
| 92 |
+
pipe.to(device, dtype=dtype)
|
| 93 |
+
|
| 94 |
+
print("Encoding prompt...")
|
| 95 |
+
|
| 96 |
+
prompt_embeds, pooled_prompt_embeds, text_ids = pipe.encode_prompt(
|
| 97 |
+
prompt,
|
| 98 |
+
prompt_2=prompt,
|
| 99 |
+
device=device
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
generator = torch.manual_seed(42)
|
| 104 |
+
|
| 105 |
+
height = 1024
|
| 106 |
+
width = 1024
|
| 107 |
+
|
| 108 |
+
print("Generating image...")
|
| 109 |
+
|
| 110 |
+
# Fix a bug in diffusers/torch
|
| 111 |
+
def callback_on_step_end(pipe, i, t, callback_kwargs):
|
| 112 |
+
latents = callback_kwargs["latents"]
|
| 113 |
+
if latents.dtype != dtype:
|
| 114 |
+
latents = latents.to(dtype)
|
| 115 |
+
return {"latents": latents}
|
| 116 |
+
img = pipe(
|
| 117 |
+
prompt_embeds=prompt_embeds,
|
| 118 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 119 |
+
height=height,
|
| 120 |
+
width=height,
|
| 121 |
+
num_inference_steps=30,
|
| 122 |
+
guidance_scale=3.5,
|
| 123 |
+
generator=generator,
|
| 124 |
+
callback_on_step_end=callback_on_step_end,
|
| 125 |
+
).images[0]
|
| 126 |
+
|
| 127 |
+
img.save(img_output_path)
|
| 128 |
+
print(f"Image saved to {img_output_path}")
|
| 129 |
+
|
| 130 |
+
print("Encoding image...")
|
| 131 |
+
# img is a PIL image. convert it to a -1 to 1 tensor
|
| 132 |
+
img = pil_to_tensor(img)
|
| 133 |
+
img = img.unsqueeze(0) # add batch dimension
|
| 134 |
+
img = img * 2 - 1 # convert to -1 to 1 range
|
| 135 |
+
img = img.to(device, dtype=dtype)
|
| 136 |
+
latents = vae.encode(img).latent_dist.sample()
|
| 137 |
+
|
| 138 |
+
shift = vae.config['shift_factor'] if vae.config['shift_factor'] is not None else 0
|
| 139 |
+
latents = vae.config['scaling_factor'] * (latents - shift)
|
| 140 |
+
|
| 141 |
+
num_channels_latents = pipe.transformer.config.in_channels // 4
|
| 142 |
+
|
| 143 |
+
l_height = 2 * (int(height) // (pipe.vae_scale_factor * 2))
|
| 144 |
+
l_width = 2 * (int(width) // (pipe.vae_scale_factor * 2))
|
| 145 |
+
packed_latents = pipe._pack_latents(latents, 1, num_channels_latents, l_height, l_width)
|
| 146 |
+
|
| 147 |
+
packed_latents, latent_image_ids = pipe.prepare_latents(
|
| 148 |
+
1,
|
| 149 |
+
num_channels_latents,
|
| 150 |
+
height,
|
| 151 |
+
width,
|
| 152 |
+
prompt_embeds.dtype,
|
| 153 |
+
device,
|
| 154 |
+
generator,
|
| 155 |
+
packed_latents,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
print("Calculating timestep weights...")
|
| 159 |
+
|
| 160 |
+
torch.manual_seed(8675309)
|
| 161 |
+
noise = torch.randn_like(packed_latents, device=device, dtype=dtype)
|
| 162 |
+
|
| 163 |
+
# Create linear timesteps from 1000 to 0
|
| 164 |
+
num_train_timesteps = 1000
|
| 165 |
+
timesteps_torch = torch.linspace(1000, 1, num_train_timesteps, device='cpu')
|
| 166 |
+
timesteps = np.linspace(1, num_train_timesteps, num_train_timesteps, dtype=np.float32)[::-1].copy()
|
| 167 |
+
timesteps = torch.from_numpy(timesteps).to(dtype=torch.float32)
|
| 168 |
+
|
| 169 |
+
timestep_weights = torch.zeros(num_train_timesteps, dtype=torch.float32, device=device)
|
| 170 |
+
|
| 171 |
+
guidance = torch.full([1], 1.0, device=device, dtype=torch.float32)
|
| 172 |
+
guidance = guidance.expand(latents.shape[0])
|
| 173 |
+
|
| 174 |
+
pbar = tqdm(range(num_train_timesteps), desc="loss: 0.000000 scaler: 0.0000")
|
| 175 |
+
for i in pbar:
|
| 176 |
+
timestep = timesteps[i:i+1].to(device)
|
| 177 |
+
t_01 = (timestep / 1000).to(device)
|
| 178 |
+
t_01 = t_01.reshape(-1, 1, 1)
|
| 179 |
+
noisy_latents = (1.0 - t_01) * packed_latents + t_01 * noise
|
| 180 |
+
|
| 181 |
+
noise_pred = pipe.transformer(
|
| 182 |
+
hidden_states=noisy_latents, # torch.Size([1, 4096, 64])
|
| 183 |
+
timestep=timestep / 1000,
|
| 184 |
+
guidance=guidance,
|
| 185 |
+
pooled_projections=pooled_prompt_embeds,
|
| 186 |
+
encoder_hidden_states=prompt_embeds,
|
| 187 |
+
txt_ids=text_ids,
|
| 188 |
+
img_ids=latent_image_ids,
|
| 189 |
+
return_dict=False,
|
| 190 |
+
)[0]
|
| 191 |
+
|
| 192 |
+
target = noise - packed_latents
|
| 193 |
+
|
| 194 |
+
loss = torch.nn.functional.mse_loss(noise_pred.float(), target.float())
|
| 195 |
+
loss = loss
|
| 196 |
+
|
| 197 |
+
# determine scaler to multiply loss by to make it 1
|
| 198 |
+
scaler = 1.0 / (loss + 1e-6)
|
| 199 |
+
|
| 200 |
+
timestep_weights[i] = scaler
|
| 201 |
+
pbar.set_description(f"loss: {loss.item():.6f} scaler: {scaler.item():.4f}")
|
| 202 |
+
|
| 203 |
+
print("normalizing timestep weights...")
|
| 204 |
+
# normalize the timestep weights so they are a mean of 1.0
|
| 205 |
+
timestep_weights = timestep_weights / timestep_weights.mean()
|
| 206 |
+
timestep_weights = timestep_weights.cpu().numpy().tolist()
|
| 207 |
+
|
| 208 |
+
print("Saving timestep weights...")
|
| 209 |
+
|
| 210 |
+
with open(output_path, 'w') as f:
|
| 211 |
+
json.dump(timestep_weights, f)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
print(f"Timestep weights saved to {output_path}")
|
| 215 |
+
print("Done!")
|
| 216 |
+
flush()
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
|