File size: 6,091 Bytes
362588a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | import argparse
import os
import random
import sys
import torch
from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionXLPipeline
from huggingface_hub import hf_hub_download, login
from PIL import Image
RUN_DIR = os.environ.get("RUN_DIR", "/content")
DATA_DIR = os.environ.get("DATA_DIR", "").strip() or os.path.join(RUN_DIR, ".img")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--dataset_repo", default="RASHID778/king2-image-dataset")
ap.add_argument("--lora_repo", default="RASHID778/king2-image")
ap.add_argument("--base_model", default="stabilityai/stable-diffusion-xl-base-1.0")
ap.add_argument("--vae", default="madebyollin/sdxl-vae-fp16-fix")
ap.add_argument("--resolution", type=int, default=512)
ap.add_argument("--lr", type=float, default=1e-4)
ap.add_argument("--train_steps", type=int, default=3)
ap.add_argument("--grad_accum", type=int, default=4)
ap.add_argument("--seed", type=int, default=0)
args = ap.parse_args()
torch.manual_seed(args.seed)
random.seed(args.seed)
login(token=os.environ["HF_TOKEN"])
device = "cuda"
dtype = torch.float16
sys.path.insert(0, RUN_DIR)
import train_continue as tc
data_dir = tc.download_dataset(args.dataset_repo)
rows, actual = tc.load_rows(data_dir)
vae = AutoencoderKL.from_pretrained(args.vae)
pipe = StableDiffusionXLPipeline.from_pretrained(
args.base_model,
vae=vae,
torch_dtype=dtype,
variant="fp16",
use_safetensors=True,
safety_checker=None,
requires_safety_checker=False,
)
pipe.load_lora_weights(args.lora_repo, weight_name="pytorch_lora_weights.safetensors")
pipe.vae.to(dtype=torch.float32)
scheduler = DDPMScheduler.from_pretrained(args.base_model, subfolder="scheduler")
print("[steps] models loaded", flush=True)
unet = pipe.unet.to(device)
pipe.vae.to(device)
pipe.text_encoder.to(device)
pipe.text_encoder_2.to(device)
for n, p in unet.named_parameters():
p.requires_grad_(False)
for n, p in unet.named_parameters():
if tc._is_lora_weight(n):
p.requires_grad_(True)
trainable = [p for p in unet.parameters() if p.requires_grad]
optimizer = torch.optim.AdamW(trainable, lr=args.lr, weight_decay=1e-2)
res = args.resolution
add_time_ids = torch.tensor([res, res, 0, 0, res, res]).unsqueeze(0).to(device)
def preprocess(pil: Image.Image) -> torch.Tensor:
w, h = pil.size
s = min(w, h)
pil = pil.crop(((w - s) // 2, (h - s) // 2, (w + s) // 2, (h + s) // 2))
pil = pil.resize((res, res), Image.BILINEAR)
import numpy as np
return (torch.from_numpy(np.array(pil)).float() / 127.5 - 1.0).permute(2, 0, 1)
def get_batch(idx: int):
cap = rows[idx]["text"]
fn = rows[idx]["file_name"]
sub, name = fn.split("/", 1)
img = os.path.join(actual.get(sub, os.path.join(data_dir, sub)), name)
pil = Image.open(img).convert("RGB")
pixels = preprocess(pil).unsqueeze(0).to(device)
with torch.no_grad():
out = pipe.encode_prompt(
[cap], device, num_images_per_prompt=1, do_classifier_free_guidance=False
)
if isinstance(out, dict):
pe, pooled = out["prompt_embeds"], out["pooled_prompt_embeds"]
elif len(out) == 4:
pe, pooled = out[0], out[2]
else:
pe, pooled = out[0], out[1]
lat = pipe.vae.encode(pixels).latent_dist.sample() * pipe.vae.config.scaling_factor
return lat.to(dtype), pe, pooled, fn
def fin(x) -> str:
if x is None:
return "?"
b = torch.isfinite(x).all().item()
v = x.abs().max().item() if x.numel() else 0.0
return f"fin={b}(a={v:.2f})"
pos = 0
print("[steps] running instrumented replication...", flush=True)
for gstep in range(args.train_steps):
optimizer.zero_grad(set_to_none=True)
for micro in range(args.grad_accum):
latents, pe, pooled, fn = get_batch(pos % len(rows))
pos += 1
noise = torch.randn_like(latents)
timesteps = torch.randint(0, scheduler.config.num_train_timesteps, (1,), device=device).long()
noisy = scheduler.add_noise(latents, noise, timesteps)
t_val = int(timesteps.item())
del latents
torch.cuda.empty_cache()
with torch.autocast(device_type="cuda", dtype=torch.float16):
pred = unet(
noisy,
timesteps,
encoder_hidden_states=pe,
added_cond_kwargs={"text_embeds": pooled, "time_ids": add_time_ids},
).sample
pred = pred.float()
loss = torch.nn.functional.mse_loss(pred, noise.float()) / args.grad_accum
loss_fin = torch.isfinite(loss).item()
is_nan = not loss_fin
print(
f"[micro] gs={gstep} m={micro} row={pos - 1} {fn} t={t_val} "
f"pe={fin(pe)} pooled={fin(pooled)} noisy={fin(noisy)} "
f"pred={fin(pred)} loss={loss.item() * args.grad_accum:.6f}{' <-- NAN' if is_nan else ''}",
flush=True,
)
if is_nan:
return
loss.backward()
nan_g = sum(1 for p in trainable if p.grad is not None and not torch.isfinite(p.grad).all().item())
if nan_g:
print(f"[grad] NON-FINITE grads on {nan_g} params at gs={gstep} m={micro} t={t_val}", flush=True)
return
gnorm = torch.nn.utils.clip_grad_norm_(trainable, 1.0)
print(f"[step] gs={gstep} gradnorm={gnorm:.4f} weights_fin="
f"{all(torch.isfinite(p).all().item() for p in trainable)}", flush=True)
optimizer.step()
print("[steps] completed cleanly - no NaN within", args.train_steps * args.grad_accum,
"micro-batches", flush=True)
if __name__ == "__main__":
main() |