File size: 17,237 Bytes
838eb19
 
 
 
 
 
 
 
 
1c5c24a
45523d8
838eb19
 
 
 
48ac172
f64b927
48ac172
838eb19
 
48ac172
838eb19
 
48ac172
 
 
 
 
838eb19
48ac172
 
 
838eb19
 
 
48ac172
 
 
 
 
 
 
 
 
 
 
838eb19
 
48ac172
 
 
838eb19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c365ce
 
838eb19
 
 
 
 
809bf94
 
838eb19
809bf94
838eb19
f64b927
809bf94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
838eb19
 
809bf94
 
 
 
 
 
 
838eb19
 
 
 
 
809bf94
838eb19
 
6b3302c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
838eb19
 
 
6b3302c
838eb19
6b3302c
 
838eb19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
809bf94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
838eb19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
809bf94
838eb19
 
 
9b42786
838eb19
 
 
 
 
 
 
 
 
e04f839
9b42786
838eb19
 
 
 
1c5c24a
 
 
45523d8
838eb19
 
 
 
 
 
 
6b3302c
838eb19
 
 
 
 
 
 
6b3302c
 
 
 
 
 
 
 
838eb19
 
7c365ce
838eb19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b42786
 
 
 
 
 
 
838eb19
 
 
 
 
809bf94
 
 
 
838eb19
 
 
 
 
 
 
 
809bf94
 
 
 
 
 
 
e04f839
809bf94
 
 
6b3302c
809bf94
 
 
838eb19
9b42786
 
838eb19
9b42786
 
838eb19
 
 
 
 
 
 
 
9b42786
 
 
 
 
 
 
 
 
 
 
 
7c365ce
 
 
 
 
 
 
 
9b42786
 
7c365ce
 
9b42786
 
 
c15f89d
9b42786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
838eb19
9b42786
838eb19
 
 
 
 
9b42786
 
838eb19
 
 
 
 
45523d8
 
 
 
 
48ac172
838eb19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48ac172
838eb19
45523d8
 
 
838eb19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import argparse
import json
import math
import os
import random

import numpy as np  # noqa: E402
import torch
from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionXLPipeline
from diffusers.models.attention import Attention
from diffusers.models.attention_processor import AttnProcessor
from huggingface_hub import HfApi, login
from PIL import Image
from safetensors.torch import save_file

RUN_DIR = os.environ.get("RUN_DIR", "/content")
DATA_DIR = os.environ.get("DATA_DIR", "").strip() or os.path.join(RUN_DIR, ".img")


def get_token() -> str:
    tok = os.environ.get("HF_TOKEN", "").strip()
    if tok:
        return tok
    for p in (
        os.path.join(RUN_DIR, "king_hf_token.txt"),
        "/content/king_hf_token.txt",
        "/content/hf_token.txt",
    ):
        if os.path.isfile(p):
            tok = open(p, encoding="utf-8-sig").read().strip()
            if tok:
                return tok
    try:
        from google.colab import userdata

        tok = str(userdata.get("HF_TOKEN") or "").strip()
        if tok:
            return tok
    except Exception:
        pass
    try:
        from kaggle_secrets import UserSecretsClient

        tok = str(UserSecretsClient().get_secret("HF_TOKEN") or "").strip()
        if tok:
            return tok
    except Exception:
        pass
    raise RuntimeError(
        f"HF_TOKEN not found (env, {RUN_DIR}/king_hf_token.txt, Colab or Kaggle secret 'HF_TOKEN')"
    )


def build_parser():
    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("--lora_weight_file", default="pytorch_lora_weights.safetensors")
    ap.add_argument("--output_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("--grad_accum", type=int, default=4)
    ap.add_argument("--max_train_steps", type=int, default=2000)
    ap.add_argument("--checkpointing_steps", type=int, default=500)
    ap.add_argument("--lr", type=float, default=1e-4)
    ap.add_argument("--warmup_steps", type=int, default=100)
    ap.add_argument("--rank", type=int, default=16)
    ap.add_argument("--alpha", type=int, default=16)
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--max_grad_norm", type=float, default=1.0)
    ap.add_argument("--loss_cap", type=float, default=100.0)
    ap.add_argument("--pred_cap", type=float, default=1000.0)
    ap.add_argument("--keep_checkpoints", action="store_true")
    return ap


def download_dataset(repo_id: str) -> str:
    import shutil
    import tarfile

    from huggingface_hub import hf_hub_download

    data_dir = DATA_DIR
    if os.path.isdir(os.path.join(data_dir, "indoor")) or os.path.isdir(
        os.path.join(data_dir, "Indoor")
    ):
        return data_dir
    os.makedirs(data_dir, exist_ok=True)
    arc = hf_hub_download(repo_id=repo_id, filename="images/images.tar.gz", repo_type="dataset")
    print(f"[dataset] archive size {os.path.getsize(arc)}", flush=True)
    with tarfile.open(arc, "r:gz") as t:
        t.extractall(data_dir)
    meta = hf_hub_download(repo_id=repo_id, filename="metadata.jsonl", repo_type="dataset")
    shutil.copy(meta, os.path.join(data_dir, "metadata.jsonl"))
    print(f"[dataset] extracted to {data_dir}", flush=True)
    return data_dir


def load_rows(data_dir: str) -> tuple[list[dict], dict]:
    meta = os.path.join(data_dir, "metadata.jsonl")
    rows = []
    actual = {}
    for sub in ("indoor", "outdoor"):
        subdir = os.path.join(data_dir, sub)
        if not os.path.isdir(subdir):
            subdir = os.path.join(data_dir, sub.capitalize())
        if os.path.isdir(subdir):
            actual[sub] = subdir
    for line in open(meta, encoding="utf-8"):
        row = json.loads(line)
        if row.get("text"):
            rows.append(row)
    print(f"[dataset] {len(rows)} captioned rows", flush=True)
    return rows, actual


def _lora_module(name: str) -> str:
    base = name
    for token in ("lora_A", "lora_B", "lora_dense", "lora"):
        idx = base.find("." + token)
        if idx != -1:
            base = base[:idx]
            break
    return base


def _is_lora_weight(name: str) -> bool:
    return "lora" in name and name.endswith("weight")


def _lora_kind(name: str) -> str:
    if any(s in name for s in ("lora_dense1", "lora_A", ".lora.down", "lora.down.")):
        return "down"
    return "up"


def collect_lora_state_dict(model) -> dict:
    sd = {}
    for name, p in model.named_parameters():
        if not _is_lora_weight(name):
            continue
        kind = _lora_kind(name)
        key = f"{_lora_module(name)}.lora.{kind}.weight"
        for prefix in ("base_model.model.", "unet."):
            if key.startswith(prefix):
                key = key[len(prefix):]
        if not key.startswith("unet."):
            key = "unet." + key
        sd[key] = p.detach().to("cpu", dtype=torch.float16)
    return sd


def build_adapter_config(targets: list[str], rank: int, alpha: int, base: str) -> dict:
    return {
        "adapter_name": "king2",
        "alpha_pattern": {},
        "auto_mapping": None,
        "base_model_name_or_path": base,
        "bias": "none",
        "fan_in_fan_out": False,
        "inference_mode": True,
        "init_lora_weights": True,
        "layer_replication": None,
        "layers_pattern": None,
        "layers_to_transform": None,
        "loops": None,
        "megatron_config": None,
        "megatron_cfg": None,
        "modules_to_save": None,
        "non_lora_submodules": None,
        "peft_type": "LORA",
        "r": rank,
        "rank_pattern": {},
        "revision": None,
        "target_modules": targets,
        "task_type": None,
        "use_dora": False,
        "use_rslora": False,
    }


def latest_checkpoint_step(api: HfApi, repo_id: str) -> int:
    best = 0
    try:
        files = api.list_repo_files(repo_id)
    except Exception:
        return best
    prefix = "checkpoint-continue-"
    for f in files:
        if f.startswith(prefix) and f.endswith("/pytorch_lora_weights.safetensors"):
            try:
                step = int(f.split(prefix, 1)[1].split("/", 1)[0])
                best = max(best, step)
            except ValueError:
                pass
    return best


def main() -> None:
    args = build_parser().parse_args()

    torch.manual_seed(args.seed)
    random.seed(args.seed)
    login(token=get_token())

    device = "cuda"
    dtype = torch.float16

    print(
        f"[conf] base={args.base_model} vae={args.vae} res={args.resolution} "
        f"steps={args.max_train_steps} lr={args.lr} rank={args.rank} accum={args.grad_accum}",
        flush=True,
    )

    data_dir = download_dataset(args.dataset_repo)
    rows, actual = load_rows(data_dir)
    if not rows:
        raise SystemExit("no captioned rows in dataset - run caption step first")

    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=args.lora_weight_file)
    pipe.vae.to(dtype=torch.float32)
    scheduler = DDPMScheduler.from_pretrained(args.base_model, subfolder="scheduler")
    print("[lora] loaded RASHID778/king2-image onto UNet", flush=True)

    unet = pipe.unet.to(device)
    for _m in unet.modules():
        if isinstance(_m, Attention):
            _m.upcast_attention = True
    unet.set_attn_processor(AttnProcessor())
    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 _is_lora_weight(n):
            p.requires_grad_(True)

    trainable = [p for p in unet.parameters() if p.requires_grad]
    n_params = sum(p.numel() for p in trainable)
    print(f"[params] trainable params: {n_params/1e6:.2f}M", flush=True)

    lora_targets = sorted(
    {
        _lora_module(name)
        .removeprefix("unet.")
        .removeprefix("base_model.model.")
        for name, _ in unet.named_parameters()
        if _is_lora_weight(name)
    }
)
    saved_cfg = build_adapter_config(lora_targets, args.rank, args.alpha, args.base_model)

    optimizer = torch.optim.AdamW(trainable, lr=args.lr, weight_decay=1e-2, eps=1e-6)
    total_updates = args.max_train_steps

    def warmup_cosine(step: int) -> float:
        if step < args.warmup_steps:
            return step / max(1, args.warmup_steps)
        prog = (step - args.warmup_steps) / max(1, total_updates - args.warmup_steps)
        return 0.5 * (1.0 + math.cos(math.pi * min(1.0, prog)))

    lr_scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, warmup_cosine)

    res = args.resolution

    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)
        return (torch.from_numpy(np.array(pil)).float() / 127.5 - 1.0).permute(2, 0, 1)

    def encode_prompt(texts: list[str]):
        with torch.no_grad():
            out = pipe.encode_prompt(
                texts, device, num_images_per_prompt=1, do_classifier_free_guidance=False
            )
        if isinstance(out, dict):
            return out["prompt_embeds"], out["pooled_prompt_embeds"]
        if len(out) == 4:
            return out[0], out[2]
        return out[0], out[1]

    def encode_latents(pixels: torch.Tensor) -> torch.Tensor:
        with torch.no_grad():
            latents = pipe.vae.encode(pixels).latent_dist.sample()
        latents = latents * pipe.vae.config.scaling_factor
        if not torch.isfinite(latents).all():
            raise RuntimeError(
                f"[vae] non-finite latents at row {pos % len(rows)} (fn {rows[pos % len(rows)]['file_name']})"
            )
        return latents.to(dtype)

    add_time_ids = torch.tensor([res, res, 0, 0, res, res]).unsqueeze(0).to(device)

    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)
        prompt_embeds, pooled = encode_prompt([cap])
        latents = encode_latents(pixels)
        return latents, prompt_embeds, pooled

    pos = 0
    running_loss = 0.0
    api = HfApi()
    global_step = latest_checkpoint_step(api, args.output_repo)
    if global_step >= total_updates:
        raise SystemExit(f"training already complete (latest checkpoint at step {global_step})")
    if global_step > 0:
        weight = f"checkpoint-continue-{global_step}/pytorch_lora_weights.safetensors"
        say = f"[resume] continuing from checkpoint-continue-{global_step} (step {global_step}/{total_updates})"
        print(say, flush=True)
        pipe.load_lora_weights(args.output_repo, weight_name=weight)
        for n, p in unet.named_parameters():
            p.requires_grad_(False)
        for n, p in unet.named_parameters():
            if _is_lora_weight(n):
                p.requires_grad_(True)
        trainable.clear()
        trainable.extend([p for p in unet.parameters() if p.requires_grad])

    skipped = 0

    while global_step < total_updates:
        optimizer.zero_grad(set_to_none=True)
        step_loss = 0.0
        for _micro in range(args.grad_accum):
            latents, prompt_embeds, pooled = 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)
            with torch.autocast(device_type="cuda", dtype=torch.float16):
                pred = unet(
                    noisy,
                    timesteps,
                    encoder_hidden_states=prompt_embeds,
                    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_val = float(loss)
            pred_max = float(pred.abs().max())
            if (
                not torch.isfinite(loss)
                or not torch.isfinite(pred).all().item()
                or loss_val > args.loss_cap
                or pred_max > args.pred_cap
            ):
                skipped += 1
                print(
                    f"[warn] unstable loss at step {global_step} micro {_micro} "
                    f"row {pos - 1} loss={loss_val:.3f} pred_max={pred_max:.3f} - skipped",
                    flush=True,
                )
                continue
            loss.backward()
            step_loss += loss.item() * args.grad_accum
            if global_step == 0 and _micro == 0:
                print(
                    f"[diag] step0 row={pos - 1} fn={rows[pos - 1]['file_name']} "
                    f"latents_finite={torch.isfinite(latents).all().item()} "
                    f"pred_finite={pred.isfinite().all().item()} loss={loss.item() * args.grad_accum:.6f}",
                    flush=True,
                )
        grad_finite = all(
            p.grad is None or torch.isfinite(p.grad).all() for p in trainable
        )
        if grad_finite:
            torch.nn.utils.clip_grad_norm_(trainable, args.max_grad_norm)
            optimizer.step()
            lr_scheduler.step()
        else:
            skipped += 1
            optimizer.zero_grad(set_to_none=True)
            print(f"[warn] non-finite grads at step {global_step} - step skipped", flush=True)
        global_step += 1
        running_loss += step_loss

        if global_step % 25 == 0 or global_step == total_updates:
            print(
                f"[step] {global_step}/{total_updates} "
                f"loss={running_loss / min(25, global_step):.4f} "
                f"lr={lr_scheduler.get_last_lr()[0]:.2e} "
                f"skipped={skipped}",
                flush=True,
            )
            running_loss = 0.0

        if args.checkpointing_steps and global_step % args.checkpointing_steps == 0:
            bad = sum(1 for p in trainable if not torch.isfinite(p).all().item())
            if bad:
                raise SystemExit(
                    f"ABORT: {bad} non-finite trainable weights at step {global_step} - refusing to checkpoint/upload"
                )
            save_dir = os.path.join(RUN_DIR, f"ckpt-{global_step}")
            os.makedirs(save_dir, exist_ok=True)
            sd = collect_lora_state_dict(unet)
            save_file(sd, os.path.join(save_dir, "pytorch_lora_weights.safetensors"))
            with open(os.path.join(save_dir, "adapter_config.json"), "w", encoding="utf-8") as fh:
                json.dump(saved_cfg, fh, indent=2)
            print(f"[ckpt] saved locally {save_dir} ({len(sd)} tensors)", flush=True)
            if args.keep_checkpoints:
                api.upload_folder(
                    repo_id=args.output_repo,
                    folder_path=save_dir,
                    path_in_repo=f"checkpoint-continue-{global_step}",
                    commit_message=f"continuation checkpoint {global_step}",
                )
                print(f"[ckpt] pushed checkpoint-continue-{global_step}", flush=True)
            sd.clear()
            del sd
            torch.cuda.empty_cache()

    final_dir = os.path.join(RUN_DIR, "king2-final")
    os.makedirs(final_dir, exist_ok=True)
    bad_final = sum(1 for p in trainable if not torch.isfinite(p).all().item())
    if bad_final:
        raise SystemExit(f"ABORT: {bad_final} non-finite trainable weights at end of training - refusing to upload")
    final_sd = collect_lora_state_dict(unet)
    save_file(final_sd, os.path.join(final_dir, "pytorch_lora_weights.safetensors"))
    with open(os.path.join(final_dir, "adapter_config.json"), "w", encoding="utf-8") as fh:
        json.dump(saved_cfg, fh, indent=2)
    print(f"[done] trained {global_step} steps; final LoRA saved locally", flush=True)

    print("[upload] pushing final weights to", args.output_repo, flush=True)
    api.upload_folder(
        repo_id=args.output_repo,
        folder_path=final_dir,
        path_in_repo=".",
        commit_message="king2-image continuous fine-tune (indoor/outdoor dataset)",
    )
    print("[uploaded] main LoRA updated: pytorch_lora_weights.safetensors", flush=True)


if __name__ == "__main__":
    main()