Instructions to use whosouravsharma/diffusiondb-sd15-lora with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use whosouravsharma/diffusiondb-sd15-lora with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.bfloat16, device_map="cuda") pipe.load_lora_weights("whosouravsharma/diffusiondb-sd15-lora") prompt = "a anthropomorphic lion wizard, diffuse lighting, fantasy, intricate, elegant, highly detailed, lifelike, photorealistic, digital painting, artstation, illustration, concept art, smooth, sharp focus, naturalism, trending on byron's - muse, by greg rutkowski and greg staples" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- Draw Things
- DiffusionBee
Add the training scripts that produced these checkpoints
Browse files- training/cache_latents_job.py +222 -0
- training/main.py +109 -0
- training/sample_job.py +123 -0
- training/train_lora_job.py +369 -0
training/cache_latents_job.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 9 |
+
# "pillow",
|
| 10 |
+
# "numpy",
|
| 11 |
+
# "pyarrow",
|
| 12 |
+
# ]
|
| 13 |
+
# ///
|
| 14 |
+
"""Stage 1 of training: VAE-encode the dataset once, so the training loop
|
| 15 |
+
never runs the VAE or decodes a PNG again.
|
| 16 |
+
|
| 17 |
+
hf jobs uv run --flavor a10g-small --timeout 2h --secrets HF_TOKEN \\
|
| 18 |
+
training/cache_latents_job.py
|
| 19 |
+
|
| 20 |
+
Reads whosouravsharma/text-to-image-diffusiondb-2M @ v2-clean (~9.4 GB)
|
| 21 |
+
Writes whosouravsharma/text-to-image-diffusiondb-2M @ latents-512 (~0.9 GB)
|
| 22 |
+
|
| 23 |
+
Why this exists: each training epoch would otherwise decode 618 KB of PNG per
|
| 24 |
+
image and run the VAE encoder over it. Doing it once turns a 9.4 GB
|
| 25 |
+
random-read image dataset into ~0.9 GB of tensors that fit in page cache.
|
| 26 |
+
|
| 27 |
+
Two decisions baked in here, both expensive to change afterwards because
|
| 28 |
+
latents are resolution-specific:
|
| 29 |
+
|
| 30 |
+
* 512x512 centre crop, no aspect bucketing. At ~14.6k images the buckets
|
| 31 |
+
would be too thin to batch cleanly.
|
| 32 |
+
* mean AND logvar are stored, not just the mean. The training loop is
|
| 33 |
+
supposed to sample from the posterior; caching only the mean silently
|
| 34 |
+
removes that noise. 64 KB/image instead of 32 KB - not worth the loss.
|
| 35 |
+
|
| 36 |
+
The 0.18215 scaling factor is deliberately NOT applied here. It belongs in
|
| 37 |
+
the training loop, applied after sampling, so the cache stays a faithful
|
| 38 |
+
record of what the VAE produced. It is recorded in the manifest.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
import io
|
| 42 |
+
import json
|
| 43 |
+
import os
|
| 44 |
+
from pathlib import Path
|
| 45 |
+
|
| 46 |
+
import numpy as np
|
| 47 |
+
import pyarrow as pa
|
| 48 |
+
import pyarrow.parquet as pq
|
| 49 |
+
import torch
|
| 50 |
+
from datasets import Image as HFImage
|
| 51 |
+
from datasets import load_dataset
|
| 52 |
+
from diffusers import AutoencoderKL
|
| 53 |
+
from huggingface_hub import HfApi
|
| 54 |
+
from PIL import Image
|
| 55 |
+
|
| 56 |
+
SOURCE_REPO = "whosouravsharma/text-to-image-diffusiondb-2M"
|
| 57 |
+
SOURCE_REVISION = os.environ.get("SOURCE_REVISION", "v2-clean")
|
| 58 |
+
TARGET_REVISION = os.environ.get("TARGET_REVISION", "latents-512")
|
| 59 |
+
|
| 60 |
+
# sd-vae-ft-mse rather than SD 1.5's original VAE: drop-in compatible, better
|
| 61 |
+
# reconstruction, and it is what most SD 1.5 fine-tunes use.
|
| 62 |
+
VAE_REPO = "stabilityai/sd-vae-ft-mse"
|
| 63 |
+
|
| 64 |
+
RESOLUTION = int(os.environ.get("RESOLUTION", 512))
|
| 65 |
+
BATCH_SIZE = int(os.environ.get("BATCH_SIZE", 16))
|
| 66 |
+
SHARD_ROWS = 4000
|
| 67 |
+
|
| 68 |
+
OUT_DIR = Path("latents")
|
| 69 |
+
|
| 70 |
+
SCHEMA = pa.schema([
|
| 71 |
+
("image_name", pa.string()),
|
| 72 |
+
("prompt", pa.string()),
|
| 73 |
+
("latent_mean", pa.binary()), # float16, (4, 64, 64), C-order
|
| 74 |
+
("latent_logvar", pa.binary()),
|
| 75 |
+
])
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def center_crop(image: Image.Image, size: int) -> Image.Image:
|
| 79 |
+
"""Resize the short side to `size`, then crop the centre square.
|
| 80 |
+
|
| 81 |
+
Anything non-square loses its edges. That is the cost of skipping aspect
|
| 82 |
+
bucketing and it is a real loss on the ~49% that are not square.
|
| 83 |
+
"""
|
| 84 |
+
image = image.convert("RGB")
|
| 85 |
+
width, height = image.size
|
| 86 |
+
scale = size / min(width, height)
|
| 87 |
+
if scale != 1.0:
|
| 88 |
+
image = image.resize(
|
| 89 |
+
(max(size, round(width * scale)), max(size, round(height * scale))),
|
| 90 |
+
Image.BICUBIC,
|
| 91 |
+
)
|
| 92 |
+
width, height = image.size
|
| 93 |
+
left = (width - size) // 2
|
| 94 |
+
top = (height - size) // 2
|
| 95 |
+
return image.crop((left, top, left + size, top + size))
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def to_tensor(image: Image.Image) -> torch.Tensor:
|
| 99 |
+
array = np.asarray(image, dtype=np.float32) / 127.5 - 1.0 # [-1, 1]
|
| 100 |
+
return torch.from_numpy(array).permute(2, 0, 1)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def encode_split(split: str, vae, device, dtype) -> tuple[int, list[Path]]:
|
| 104 |
+
# decode=False keeps the raw bytes and the filename; we do our own
|
| 105 |
+
# decoding so the resize/crop is explicit rather than left to the loader.
|
| 106 |
+
dataset = load_dataset(
|
| 107 |
+
SOURCE_REPO, split=split, revision=SOURCE_REVISION
|
| 108 |
+
).cast_column("image", HFImage(decode=False))
|
| 109 |
+
|
| 110 |
+
print(f"\n{split}: {len(dataset):,} rows", flush=True)
|
| 111 |
+
|
| 112 |
+
written: list[Path] = []
|
| 113 |
+
rows: list[dict] = []
|
| 114 |
+
batch: list[torch.Tensor] = []
|
| 115 |
+
meta: list[tuple[str, str]] = []
|
| 116 |
+
|
| 117 |
+
def flush_shard() -> None:
|
| 118 |
+
if not rows:
|
| 119 |
+
return
|
| 120 |
+
path = OUT_DIR / f"{split}-{len(written):05}.parquet"
|
| 121 |
+
pq.write_table(
|
| 122 |
+
pa.Table.from_pydict(
|
| 123 |
+
{k: [r[k] for r in rows] for k in SCHEMA.names}, schema=SCHEMA
|
| 124 |
+
),
|
| 125 |
+
path,
|
| 126 |
+
)
|
| 127 |
+
written.append(path)
|
| 128 |
+
rows.clear()
|
| 129 |
+
|
| 130 |
+
def flush_batch() -> None:
|
| 131 |
+
if not batch:
|
| 132 |
+
return
|
| 133 |
+
pixels = torch.stack(batch).to(device, dtype=dtype)
|
| 134 |
+
with torch.no_grad():
|
| 135 |
+
posterior = vae.encode(pixels).latent_dist
|
| 136 |
+
means = posterior.mean.to(torch.float16).cpu().numpy()
|
| 137 |
+
logvars = posterior.logvar.to(torch.float16).cpu().numpy()
|
| 138 |
+
for (name, prompt), mean, logvar in zip(meta, means, logvars):
|
| 139 |
+
rows.append({
|
| 140 |
+
"image_name": name,
|
| 141 |
+
"prompt": prompt,
|
| 142 |
+
"latent_mean": mean.tobytes(),
|
| 143 |
+
"latent_logvar": logvar.tobytes(),
|
| 144 |
+
})
|
| 145 |
+
batch.clear()
|
| 146 |
+
meta.clear()
|
| 147 |
+
|
| 148 |
+
for index, record in enumerate(dataset):
|
| 149 |
+
image = Image.open(io.BytesIO(record["image"]["bytes"]))
|
| 150 |
+
batch.append(to_tensor(center_crop(image, RESOLUTION)))
|
| 151 |
+
meta.append((record["image"]["path"], record["prompt"]))
|
| 152 |
+
|
| 153 |
+
if len(batch) >= BATCH_SIZE:
|
| 154 |
+
flush_batch()
|
| 155 |
+
if len(rows) >= SHARD_ROWS:
|
| 156 |
+
flush_shard()
|
| 157 |
+
if (index + 1) % 2000 == 0:
|
| 158 |
+
print(f" {index + 1:,}/{len(dataset):,}", flush=True)
|
| 159 |
+
|
| 160 |
+
flush_batch()
|
| 161 |
+
flush_shard()
|
| 162 |
+
|
| 163 |
+
total = len(written)
|
| 164 |
+
for position, path in enumerate(written):
|
| 165 |
+
path.rename(OUT_DIR / f"{split}-{position:05}-of-{total:05}.parquet")
|
| 166 |
+
print(f" {split}: {len(dataset):,} latents in {total} shard(s)")
|
| 167 |
+
return len(dataset), written
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def main() -> None:
|
| 171 |
+
if not torch.cuda.is_available():
|
| 172 |
+
raise SystemExit("No GPU. Run this on a GPU flavor, e.g. a10g-small.")
|
| 173 |
+
|
| 174 |
+
device = torch.device("cuda")
|
| 175 |
+
dtype = torch.float16
|
| 176 |
+
|
| 177 |
+
print(f"Loading VAE {VAE_REPO} ...")
|
| 178 |
+
vae = AutoencoderKL.from_pretrained(VAE_REPO, torch_dtype=dtype).to(device)
|
| 179 |
+
vae.eval()
|
| 180 |
+
vae.requires_grad_(False)
|
| 181 |
+
|
| 182 |
+
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 183 |
+
|
| 184 |
+
counts = {}
|
| 185 |
+
for split in ("train", "validation"):
|
| 186 |
+
counts[split], _ = encode_split(split, vae, device, dtype)
|
| 187 |
+
|
| 188 |
+
latent_side = RESOLUTION // 8
|
| 189 |
+
manifest = {
|
| 190 |
+
"source": f"{SOURCE_REPO}@{SOURCE_REVISION}",
|
| 191 |
+
"vae": VAE_REPO,
|
| 192 |
+
"resolution": RESOLUTION,
|
| 193 |
+
"latent_shape": [4, latent_side, latent_side],
|
| 194 |
+
"latent_dtype": "float16",
|
| 195 |
+
"stores": "posterior mean and logvar, unscaled",
|
| 196 |
+
# Apply this in the training loop, after sampling from the posterior.
|
| 197 |
+
"scaling_factor": float(vae.config.scaling_factor),
|
| 198 |
+
"crop": "resize short side then centre crop",
|
| 199 |
+
"counts": counts,
|
| 200 |
+
}
|
| 201 |
+
(OUT_DIR / "manifest.json").write_text(json.dumps(manifest, indent=2))
|
| 202 |
+
print("\n" + json.dumps(manifest, indent=2))
|
| 203 |
+
|
| 204 |
+
api = HfApi()
|
| 205 |
+
api.create_branch(
|
| 206 |
+
repo_id=SOURCE_REPO, branch=TARGET_REVISION,
|
| 207 |
+
repo_type="dataset", exist_ok=True,
|
| 208 |
+
)
|
| 209 |
+
api.upload_folder(
|
| 210 |
+
folder_path=str(OUT_DIR),
|
| 211 |
+
path_in_repo="data",
|
| 212 |
+
repo_id=SOURCE_REPO,
|
| 213 |
+
repo_type="dataset",
|
| 214 |
+
revision=TARGET_REVISION,
|
| 215 |
+
delete_patterns="*",
|
| 216 |
+
commit_message=f"Cache {RESOLUTION}px VAE latents from {SOURCE_REVISION}",
|
| 217 |
+
)
|
| 218 |
+
print(f"\nPushed to {SOURCE_REPO} @ {TARGET_REVISION}. Done.")
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
main()
|
training/main.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Launches the training stages on Hugging Face Jobs.
|
| 2 |
+
|
| 3 |
+
python3 main.py baseline render vanilla SD 1.5 on the eval prompts
|
| 4 |
+
python3 main.py latents VAE-encode the dataset once
|
| 5 |
+
python3 main.py train LoRA fine-tune on the cached latents
|
| 6 |
+
python3 main.py sample checkpoint-2000
|
| 7 |
+
|
| 8 |
+
Everything runs on HF infrastructure; the M2 has no usable GPU. No -v volume
|
| 9 |
+
is passed - each job pulls what it needs from the Hub itself.
|
| 10 |
+
|
| 11 |
+
Order matters: `baseline` first (so there is something to compare against),
|
| 12 |
+
then `latents`, then `train`, then `sample` per checkpoint.
|
| 13 |
+
|
| 14 |
+
Per-run overrides go through the environment rather than flags here, since
|
| 15 |
+
each job script already reads its own constants that way:
|
| 16 |
+
|
| 17 |
+
EPOCHS=20 python3 main.py train
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import os
|
| 21 |
+
import subprocess
|
| 22 |
+
import sys
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
HERE = Path(__file__).resolve().parent
|
| 26 |
+
|
| 27 |
+
# Job scripts are self-contained PEP-723 files. They ship to HF standalone
|
| 28 |
+
# and cannot import from this repo, so each carries its own constants and
|
| 29 |
+
# writes them into a manifest - no shared config module to drift out of sync.
|
| 30 |
+
STAGES = {
|
| 31 |
+
"latents": (HERE / "cache_latents_job.py", "a10g-small", "2h"),
|
| 32 |
+
"train": (HERE / "train_lora_job.py", "a10g-small", "6h"),
|
| 33 |
+
"sample": (HERE / "sample_job.py", "a10g-small", "1h"),
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
# Variables worth forwarding to the job if they are set locally.
|
| 37 |
+
FORWARDED = [
|
| 38 |
+
"RESOLUTION", "EPOCHS", "BATCH_SIZE", "GRAD_ACCUM", "LEARNING_RATE",
|
| 39 |
+
"LORA_RANK", "LORA_ALPHA", "CAPTION_DROPOUT", "CHECKPOINT_EVERY",
|
| 40 |
+
"RESUME_FROM", "SEED", "CHECKPOINT", "STEPS", "GUIDANCE",
|
| 41 |
+
"LATENTS_REVISION", "SOURCE_REVISION", "TARGET_REVISION", "MODEL_REPO",
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
DATASET_REPO = "whosouravsharma/text-to-image-diffusiondb-2M"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def require_latents() -> None:
|
| 49 |
+
"""Refuse to launch training before stage 1 has produced latents.
|
| 50 |
+
|
| 51 |
+
Checked here rather than only inside the job: a GPU job that dies on a
|
| 52 |
+
missing branch still costs a scheduling round-trip, and the failure shows
|
| 53 |
+
up as a 404 traceback rather than as the one line that explains it.
|
| 54 |
+
"""
|
| 55 |
+
from huggingface_hub import HfApi
|
| 56 |
+
|
| 57 |
+
revision = os.environ.get("LATENTS_REVISION", "latents-512")
|
| 58 |
+
branches = [
|
| 59 |
+
b.name for b in
|
| 60 |
+
HfApi().list_repo_refs(DATASET_REPO, repo_type="dataset").branches
|
| 61 |
+
]
|
| 62 |
+
if revision not in branches:
|
| 63 |
+
raise SystemExit(
|
| 64 |
+
f"No '{revision}' branch on {DATASET_REPO}.\n"
|
| 65 |
+
f"Existing branches: {', '.join(branches)}\n\n"
|
| 66 |
+
f"Cache the latents first:\n"
|
| 67 |
+
f" python3 main.py latents"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def run_stage(stage: str, checkpoint: str | None = None) -> int:
|
| 72 |
+
if stage == "baseline":
|
| 73 |
+
stage, checkpoint = "sample", "base"
|
| 74 |
+
if stage not in STAGES:
|
| 75 |
+
raise SystemExit(
|
| 76 |
+
f"Unknown stage {stage!r}. "
|
| 77 |
+
f"Choose from: baseline, {', '.join(STAGES)}"
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
if stage == "train":
|
| 81 |
+
require_latents()
|
| 82 |
+
|
| 83 |
+
script, flavor, timeout = STAGES[stage]
|
| 84 |
+
|
| 85 |
+
command = [
|
| 86 |
+
"hf", "jobs", "uv", "run",
|
| 87 |
+
"--flavor", flavor,
|
| 88 |
+
"--timeout", timeout,
|
| 89 |
+
"--secrets", "HF_TOKEN",
|
| 90 |
+
]
|
| 91 |
+
if checkpoint:
|
| 92 |
+
command += ["--env", f"CHECKPOINT={checkpoint}"]
|
| 93 |
+
for key in FORWARDED:
|
| 94 |
+
if key in os.environ and not (checkpoint and key == "CHECKPOINT"):
|
| 95 |
+
command += ["--env", f"{key}={os.environ[key]}"]
|
| 96 |
+
command.append(str(script))
|
| 97 |
+
|
| 98 |
+
print("=" * 60)
|
| 99 |
+
print(f"TRAINING STAGE: {stage}" + (f" ({checkpoint})" if checkpoint else ""))
|
| 100 |
+
print("=" * 60)
|
| 101 |
+
print("\nRunning:", " ".join(command), "\n")
|
| 102 |
+
|
| 103 |
+
return subprocess.call(command)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
if len(sys.argv) < 2:
|
| 108 |
+
raise SystemExit(__doc__)
|
| 109 |
+
sys.exit(run_stage(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None))
|
training/sample_job.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.10"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "torch",
|
| 5 |
+
# "diffusers>=0.31",
|
| 6 |
+
# "transformers>=4.44",
|
| 7 |
+
# "peft>=0.13",
|
| 8 |
+
# "huggingface_hub>=0.24",
|
| 9 |
+
# "pillow",
|
| 10 |
+
# ]
|
| 11 |
+
# ///
|
| 12 |
+
"""Stage 3 of training: render the held-out eval prompts from a checkpoint.
|
| 13 |
+
|
| 14 |
+
# baseline, before training - run this FIRST
|
| 15 |
+
hf jobs uv run --flavor a10g-small --timeout 1h --secrets HF_TOKEN \\
|
| 16 |
+
-e CHECKPOINT=base training/sample_job.py
|
| 17 |
+
|
| 18 |
+
# any checkpoint afterwards
|
| 19 |
+
hf jobs uv run --flavor a10g-small --timeout 1h --secrets HF_TOKEN \\
|
| 20 |
+
-e CHECKPOINT=checkpoint-2000 training/sample_job.py
|
| 21 |
+
|
| 22 |
+
Validation loss on a diffusion fine-tune correlates weakly with how the
|
| 23 |
+
output actually looks, so it cannot be the only signal. This renders the 50
|
| 24 |
+
prompts in eval_prompts.json - drawn from validation groups, so the model has
|
| 25 |
+
never trained on them - at a fixed seed, and pushes a contact sheet to the
|
| 26 |
+
model repo.
|
| 27 |
+
|
| 28 |
+
Run CHECKPOINT=base before training starts. Without a baseline you cannot
|
| 29 |
+
tell improvement from drift.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
import json
|
| 33 |
+
import os
|
| 34 |
+
from pathlib import Path
|
| 35 |
+
|
| 36 |
+
import torch
|
| 37 |
+
from diffusers import StableDiffusionPipeline
|
| 38 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 39 |
+
from PIL import Image
|
| 40 |
+
|
| 41 |
+
DATASET_REPO = "whosouravsharma/text-to-image-diffusiondb-2M"
|
| 42 |
+
DATASET_REVISION = os.environ.get("DATASET_REVISION", "v2-clean")
|
| 43 |
+
MODEL_REPO = os.environ.get("MODEL_REPO", "whosouravsharma/diffusiondb-sd15-lora")
|
| 44 |
+
|
| 45 |
+
BASE_MODEL = "runwayml/stable-diffusion-v1-5"
|
| 46 |
+
|
| 47 |
+
# "base" renders vanilla SD 1.5 with no adapter - the comparison baseline.
|
| 48 |
+
CHECKPOINT = os.environ.get("CHECKPOINT", "base")
|
| 49 |
+
|
| 50 |
+
STEPS = int(os.environ.get("STEPS", 30))
|
| 51 |
+
GUIDANCE = float(os.environ.get("GUIDANCE", 7.5))
|
| 52 |
+
SEED = int(os.environ.get("SEED", 42))
|
| 53 |
+
COLUMNS = 5
|
| 54 |
+
THUMB = 320
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def contact_sheet(images: list[Image.Image]) -> Image.Image:
|
| 58 |
+
rows = (len(images) + COLUMNS - 1) // COLUMNS
|
| 59 |
+
sheet = Image.new("RGB", (COLUMNS * THUMB, rows * THUMB), (18, 18, 22))
|
| 60 |
+
for index, image in enumerate(images):
|
| 61 |
+
sheet.paste(
|
| 62 |
+
image.resize((THUMB, THUMB), Image.LANCZOS),
|
| 63 |
+
((index % COLUMNS) * THUMB, (index // COLUMNS) * THUMB),
|
| 64 |
+
)
|
| 65 |
+
return sheet
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def main() -> None:
|
| 69 |
+
if not torch.cuda.is_available():
|
| 70 |
+
raise SystemExit("No GPU. Run this on a GPU flavor, e.g. a10g-small.")
|
| 71 |
+
|
| 72 |
+
prompts = json.loads(Path(hf_hub_download(
|
| 73 |
+
DATASET_REPO, "eval_prompts.json", repo_type="dataset",
|
| 74 |
+
revision=DATASET_REVISION,
|
| 75 |
+
)).read_text())
|
| 76 |
+
print(f"{len(prompts)} eval prompts from {DATASET_REPO}@{DATASET_REVISION}")
|
| 77 |
+
|
| 78 |
+
pipeline = StableDiffusionPipeline.from_pretrained(
|
| 79 |
+
BASE_MODEL, torch_dtype=torch.float16, safety_checker=None,
|
| 80 |
+
).to("cuda")
|
| 81 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 82 |
+
|
| 83 |
+
if CHECKPOINT != "base":
|
| 84 |
+
print(f"Loading LoRA {CHECKPOINT} ...")
|
| 85 |
+
pipeline.load_lora_weights(
|
| 86 |
+
MODEL_REPO, weight_name="pytorch_lora_weights.safetensors",
|
| 87 |
+
subfolder=CHECKPOINT,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
images = []
|
| 91 |
+
for index, prompt in enumerate(prompts):
|
| 92 |
+
# Same seed per prompt index across checkpoints, so differences come
|
| 93 |
+
# from the weights rather than from the noise.
|
| 94 |
+
generator = torch.Generator("cuda").manual_seed(SEED + index)
|
| 95 |
+
images.append(pipeline(
|
| 96 |
+
prompt, num_inference_steps=STEPS,
|
| 97 |
+
guidance_scale=GUIDANCE, generator=generator,
|
| 98 |
+
).images[0])
|
| 99 |
+
if (index + 1) % 10 == 0:
|
| 100 |
+
print(f" {index + 1}/{len(prompts)}", flush=True)
|
| 101 |
+
|
| 102 |
+
out = Path("samples") / CHECKPOINT
|
| 103 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 104 |
+
for index, image in enumerate(images):
|
| 105 |
+
image.save(out / f"{index:03}.png")
|
| 106 |
+
contact_sheet(images).save(out / "grid.jpg", quality=92)
|
| 107 |
+
(out / "prompts.json").write_text(json.dumps(
|
| 108 |
+
{"checkpoint": CHECKPOINT, "steps": STEPS, "guidance": GUIDANCE,
|
| 109 |
+
"seed": SEED, "prompts": prompts}, indent=2))
|
| 110 |
+
|
| 111 |
+
# MODEL_REPO is created ahead of time, with its card, rather than by the job.
|
| 112 |
+
api = HfApi()
|
| 113 |
+
api.upload_folder(
|
| 114 |
+
folder_path=str(out), path_in_repo=f"samples/{CHECKPOINT}",
|
| 115 |
+
repo_id=MODEL_REPO, repo_type="model",
|
| 116 |
+
commit_message=f"Eval samples for {CHECKPOINT}",
|
| 117 |
+
)
|
| 118 |
+
print(f"\nPushed to https://huggingface.co/{MODEL_REPO}"
|
| 119 |
+
f"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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.10"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "torch",
|
| 5 |
+
# "diffusers>=0.31",
|
| 6 |
+
# "transformers>=4.44",
|
| 7 |
+
# "peft>=0.13",
|
| 8 |
+
# "datasets>=2.19",
|
| 9 |
+
# "huggingface_hub>=0.24",
|
| 10 |
+
# "safetensors",
|
| 11 |
+
# "numpy",
|
| 12 |
+
# ]
|
| 13 |
+
# ///
|
| 14 |
+
"""Stage 2 of training: LoRA fine-tune SD 1.5 on the cached latents.
|
| 15 |
+
|
| 16 |
+
hf jobs uv run --flavor a10g-small --timeout 6h --secrets HF_TOKEN \\
|
| 17 |
+
training/train_lora_job.py
|
| 18 |
+
|
| 19 |
+
Reads whosouravsharma/text-to-image-diffusiondb-2M @ latents-512
|
| 20 |
+
Writes whosouravsharma/diffusiondb-sd15-lora (checkpoints + resume state)
|
| 21 |
+
|
| 22 |
+
LoRA rather than a full UNet fine-tune: 13.6k images is small, and a rank-32
|
| 23 |
+
adapter is ~10-50x cheaper to train, iterates in hours, and is revertible if
|
| 24 |
+
the result is worse. Consider a full fine-tune only once LoRA visibly
|
| 25 |
+
saturates.
|
| 26 |
+
|
| 27 |
+
Two things this script takes seriously because HF Jobs are ephemeral:
|
| 28 |
+
|
| 29 |
+
* it checkpoints to the Hub every CHECKPOINT_EVERY steps, so a timeout or a
|
| 30 |
+
preemption costs one interval, not the whole run;
|
| 31 |
+
* RESUME_FROM restores model, optimizer, scaler and step, so a restart
|
| 32 |
+
continues rather than starting over.
|
| 33 |
+
|
| 34 |
+
What is NOT cached, deliberately: per-caption text embeddings. That would be
|
| 35 |
+
~12 GB and would lock out the 10% caption dropout that classifier-free
|
| 36 |
+
guidance training needs. The text encoder is frozen and only 123M params
|
| 37 |
+
against an 860M UNet - running it inline is cheap.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
import json
|
| 41 |
+
import math
|
| 42 |
+
import os
|
| 43 |
+
import random
|
| 44 |
+
import shutil
|
| 45 |
+
from pathlib import Path
|
| 46 |
+
|
| 47 |
+
import numpy as np
|
| 48 |
+
import torch
|
| 49 |
+
import torch.nn.functional as F
|
| 50 |
+
from datasets import load_dataset
|
| 51 |
+
from diffusers import DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel
|
| 52 |
+
from diffusers.utils import convert_state_dict_to_diffusers
|
| 53 |
+
from huggingface_hub import HfApi, hf_hub_download, snapshot_download
|
| 54 |
+
from peft import LoraConfig
|
| 55 |
+
from peft.utils import get_peft_model_state_dict
|
| 56 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 57 |
+
|
| 58 |
+
DATASET_REPO = "whosouravsharma/text-to-image-diffusiondb-2M"
|
| 59 |
+
LATENTS_REVISION = os.environ.get("LATENTS_REVISION", "latents-512")
|
| 60 |
+
MODEL_REPO = os.environ.get("MODEL_REPO", "whosouravsharma/diffusiondb-sd15-lora")
|
| 61 |
+
|
| 62 |
+
BASE_MODEL = "runwayml/stable-diffusion-v1-5"
|
| 63 |
+
|
| 64 |
+
# LoRA. alpha == r keeps the effective scale at 1.0, which is the usual
|
| 65 |
+
# starting point; raise alpha to push the adapter harder at inference.
|
| 66 |
+
LORA_RANK = int(os.environ.get("LORA_RANK", 32))
|
| 67 |
+
LORA_ALPHA = int(os.environ.get("LORA_ALPHA", LORA_RANK))
|
| 68 |
+
LORA_TARGETS = ["to_k", "to_q", "to_v", "to_out.0"]
|
| 69 |
+
|
| 70 |
+
EPOCHS = int(os.environ.get("EPOCHS", 10))
|
| 71 |
+
BATCH_SIZE = int(os.environ.get("BATCH_SIZE", 8))
|
| 72 |
+
GRAD_ACCUM = int(os.environ.get("GRAD_ACCUM", 4)) # effective batch 32
|
| 73 |
+
LEARNING_RATE = float(os.environ.get("LEARNING_RATE", 1e-4))
|
| 74 |
+
WARMUP_STEPS = int(os.environ.get("WARMUP_STEPS", 500))
|
| 75 |
+
MAX_GRAD_NORM = 1.0
|
| 76 |
+
|
| 77 |
+
# Fraction of captions replaced with "" so the model learns an unconditional
|
| 78 |
+
# branch. Without this, CFG at inference has nothing to guide away from.
|
| 79 |
+
CAPTION_DROPOUT = float(os.environ.get("CAPTION_DROPOUT", 0.1))
|
| 80 |
+
|
| 81 |
+
CHECKPOINT_EVERY = int(os.environ.get("CHECKPOINT_EVERY", 500))
|
| 82 |
+
RESUME_FROM = os.environ.get("RESUME_FROM") # e.g. "checkpoint-1500"
|
| 83 |
+
SEED = int(os.environ.get("SEED", 42))
|
| 84 |
+
|
| 85 |
+
WORK_DIR = Path("run")
|
| 86 |
+
LATENT_SHAPE = (4, 64, 64)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# ---------------------------------------------------------------------------
|
| 90 |
+
# data
|
| 91 |
+
# ---------------------------------------------------------------------------
|
| 92 |
+
|
| 93 |
+
def decode_latents(blobs: list[bytes]) -> torch.Tensor:
|
| 94 |
+
array = np.stack([
|
| 95 |
+
np.frombuffer(b, dtype=np.float16).reshape(LATENT_SHAPE) for b in blobs
|
| 96 |
+
])
|
| 97 |
+
return torch.from_numpy(array.copy())
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def collate(batch: list[dict]) -> dict:
|
| 101 |
+
return {
|
| 102 |
+
"mean": decode_latents([r["latent_mean"] for r in batch]),
|
| 103 |
+
"logvar": decode_latents([r["latent_logvar"] for r in batch]),
|
| 104 |
+
"prompt": [r["prompt"] for r in batch],
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def sample_posterior(mean: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor:
|
| 109 |
+
"""Draw from N(mean, exp(logvar)) - what vae.encode().latent_dist.sample()
|
| 110 |
+
would have done had the VAE still been in the loop."""
|
| 111 |
+
logvar = logvar.clamp(-30.0, 20.0)
|
| 112 |
+
return mean + torch.exp(0.5 * logvar) * torch.randn_like(mean)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# ---------------------------------------------------------------------------
|
| 116 |
+
# checkpointing
|
| 117 |
+
# ---------------------------------------------------------------------------
|
| 118 |
+
|
| 119 |
+
def save_checkpoint(unet, optimizer, scaler, step, epoch, api, scaling_factor):
|
| 120 |
+
name = f"checkpoint-{step}"
|
| 121 |
+
out = WORK_DIR / name
|
| 122 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 123 |
+
|
| 124 |
+
lora_state = convert_state_dict_to_diffusers(get_peft_model_state_dict(unet))
|
| 125 |
+
StableDiffusionPipeline.save_lora_weights(
|
| 126 |
+
save_directory=str(out), unet_lora_layers=lora_state, safe_serialization=True
|
| 127 |
+
)
|
| 128 |
+
torch.save(
|
| 129 |
+
{"optimizer": optimizer.state_dict(), "scaler": scaler.state_dict()},
|
| 130 |
+
out / "optimizer.pt",
|
| 131 |
+
)
|
| 132 |
+
(out / "state.json").write_text(json.dumps({
|
| 133 |
+
"step": step, "epoch": epoch, "base_model": BASE_MODEL,
|
| 134 |
+
"lora_rank": LORA_RANK, "lora_alpha": LORA_ALPHA,
|
| 135 |
+
"resolution": 512, "scaling_factor": scaling_factor,
|
| 136 |
+
"learning_rate": LEARNING_RATE, "batch_size": BATCH_SIZE,
|
| 137 |
+
"grad_accum": GRAD_ACCUM, "caption_dropout": CAPTION_DROPOUT,
|
| 138 |
+
"latents": f"{DATASET_REPO}@{LATENTS_REVISION}",
|
| 139 |
+
}, indent=2))
|
| 140 |
+
|
| 141 |
+
api.upload_folder(
|
| 142 |
+
folder_path=str(out), path_in_repo=name,
|
| 143 |
+
repo_id=MODEL_REPO, repo_type="model",
|
| 144 |
+
commit_message=f"Checkpoint at step {step}",
|
| 145 |
+
)
|
| 146 |
+
shutil.rmtree(out, ignore_errors=True)
|
| 147 |
+
print(f" checkpoint pushed: {name}", flush=True)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def load_checkpoint(unet, optimizer, scaler, device):
|
| 151 |
+
print(f"Resuming from {RESUME_FROM} ...")
|
| 152 |
+
local = snapshot_download(
|
| 153 |
+
MODEL_REPO, allow_patterns=f"{RESUME_FROM}/*", repo_type="model"
|
| 154 |
+
)
|
| 155 |
+
folder = Path(local) / RESUME_FROM
|
| 156 |
+
|
| 157 |
+
unet.load_lora_adapter(str(folder / "pytorch_lora_weights.safetensors"))
|
| 158 |
+
blob = torch.load(folder / "optimizer.pt", map_location=device)
|
| 159 |
+
optimizer.load_state_dict(blob["optimizer"])
|
| 160 |
+
scaler.load_state_dict(blob["scaler"])
|
| 161 |
+
state = json.loads((folder / "state.json").read_text())
|
| 162 |
+
print(f" resumed at step {state['step']}, epoch {state['epoch']}")
|
| 163 |
+
return state["step"], state["epoch"]
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# ---------------------------------------------------------------------------
|
| 167 |
+
|
| 168 |
+
@torch.no_grad()
|
| 169 |
+
def validation_loss(unet, text_encoder, tokenizer, scheduler, loader,
|
| 170 |
+
device, dtype, scaling_factor) -> float:
|
| 171 |
+
"""Fixed-seed noise and timesteps so the number is comparable between
|
| 172 |
+
checkpoints. Diffusion val loss is a weak quality signal - the rendered
|
| 173 |
+
eval prompts from sample_job.py matter more - but it catches divergence."""
|
| 174 |
+
unet.eval()
|
| 175 |
+
generator = torch.Generator(device=device).manual_seed(SEED)
|
| 176 |
+
total, batches = 0.0, 0
|
| 177 |
+
|
| 178 |
+
for batch in loader:
|
| 179 |
+
mean = batch["mean"].to(device, torch.float32)
|
| 180 |
+
logvar = batch["logvar"].to(device, torch.float32)
|
| 181 |
+
latents = sample_posterior(mean, logvar) * scaling_factor
|
| 182 |
+
|
| 183 |
+
noise = torch.randn(latents.shape, device=device, generator=generator)
|
| 184 |
+
steps = torch.randint(
|
| 185 |
+
0, scheduler.config.num_train_timesteps, (latents.shape[0],),
|
| 186 |
+
device=device, generator=generator,
|
| 187 |
+
)
|
| 188 |
+
noisy = scheduler.add_noise(latents, noise, steps)
|
| 189 |
+
|
| 190 |
+
tokens = tokenizer(
|
| 191 |
+
batch["prompt"], padding="max_length", truncation=True,
|
| 192 |
+
max_length=tokenizer.model_max_length, return_tensors="pt",
|
| 193 |
+
).input_ids.to(device)
|
| 194 |
+
encoded = text_encoder(tokens)[0]
|
| 195 |
+
|
| 196 |
+
with torch.autocast("cuda", dtype=dtype):
|
| 197 |
+
predicted = unet(noisy, steps, encoded).sample
|
| 198 |
+
total += F.mse_loss(predicted.float(), noise.float()).item()
|
| 199 |
+
batches += 1
|
| 200 |
+
|
| 201 |
+
unet.train()
|
| 202 |
+
return total / max(batches, 1)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def main() -> None:
|
| 206 |
+
if not torch.cuda.is_available():
|
| 207 |
+
raise SystemExit("No GPU. Run this on a GPU flavor, e.g. a10g-small.")
|
| 208 |
+
|
| 209 |
+
torch.manual_seed(SEED)
|
| 210 |
+
random.seed(SEED)
|
| 211 |
+
device = torch.device("cuda")
|
| 212 |
+
dtype = torch.float16
|
| 213 |
+
WORK_DIR.mkdir(parents=True, exist_ok=True)
|
| 214 |
+
|
| 215 |
+
try:
|
| 216 |
+
manifest_path = hf_hub_download(
|
| 217 |
+
DATASET_REPO, "data/manifest.json", repo_type="dataset",
|
| 218 |
+
revision=LATENTS_REVISION,
|
| 219 |
+
)
|
| 220 |
+
except Exception as error:
|
| 221 |
+
raise SystemExit(
|
| 222 |
+
f"No cached latents at {DATASET_REPO}@{LATENTS_REVISION}.\n"
|
| 223 |
+
f"Stage 1 has to run first: python3 main.py latents\n"
|
| 224 |
+
f"({type(error).__name__})"
|
| 225 |
+
)
|
| 226 |
+
manifest = json.loads(Path(manifest_path).read_text())
|
| 227 |
+
scaling_factor = manifest["scaling_factor"]
|
| 228 |
+
print(f"latents: {manifest['latent_shape']} @ {manifest['resolution']}px, "
|
| 229 |
+
f"scaling_factor={scaling_factor}")
|
| 230 |
+
|
| 231 |
+
train_data = load_dataset(DATASET_REPO, split="train", revision=LATENTS_REVISION)
|
| 232 |
+
val_data = load_dataset(DATASET_REPO, split="validation", revision=LATENTS_REVISION)
|
| 233 |
+
print(f"train {len(train_data):,} | validation {len(val_data):,}")
|
| 234 |
+
|
| 235 |
+
train_loader = torch.utils.data.DataLoader(
|
| 236 |
+
train_data, batch_size=BATCH_SIZE, shuffle=True,
|
| 237 |
+
collate_fn=collate, num_workers=2, drop_last=True,
|
| 238 |
+
)
|
| 239 |
+
val_loader = torch.utils.data.DataLoader(
|
| 240 |
+
val_data, batch_size=BATCH_SIZE, shuffle=False, collate_fn=collate,
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
print(f"\nLoading {BASE_MODEL} ...")
|
| 244 |
+
tokenizer = CLIPTokenizer.from_pretrained(BASE_MODEL, subfolder="tokenizer")
|
| 245 |
+
text_encoder = CLIPTextModel.from_pretrained(
|
| 246 |
+
BASE_MODEL, subfolder="text_encoder", torch_dtype=dtype
|
| 247 |
+
).to(device)
|
| 248 |
+
unet = UNet2DConditionModel.from_pretrained(BASE_MODEL, subfolder="unet").to(device)
|
| 249 |
+
scheduler = DDPMScheduler.from_pretrained(BASE_MODEL, subfolder="scheduler")
|
| 250 |
+
|
| 251 |
+
text_encoder.requires_grad_(False)
|
| 252 |
+
text_encoder.eval()
|
| 253 |
+
unet.requires_grad_(False)
|
| 254 |
+
|
| 255 |
+
unet.add_adapter(LoraConfig(
|
| 256 |
+
r=LORA_RANK, lora_alpha=LORA_ALPHA,
|
| 257 |
+
init_lora_weights="gaussian", target_modules=LORA_TARGETS,
|
| 258 |
+
))
|
| 259 |
+
|
| 260 |
+
# Frozen weights in fp16 to save memory; the trainable LoRA params stay
|
| 261 |
+
# fp32 so the optimizer has the precision it needs.
|
| 262 |
+
unet.to(dtype=dtype)
|
| 263 |
+
trainable = []
|
| 264 |
+
for param in unet.parameters():
|
| 265 |
+
if param.requires_grad:
|
| 266 |
+
param.data = param.data.float()
|
| 267 |
+
trainable.append(param)
|
| 268 |
+
print(f"trainable params: {sum(p.numel() for p in trainable):,} "
|
| 269 |
+
f"of {sum(p.numel() for p in unet.parameters()):,}")
|
| 270 |
+
|
| 271 |
+
optimizer = torch.optim.AdamW(trainable, lr=LEARNING_RATE, weight_decay=1e-2)
|
| 272 |
+
scaler = torch.amp.GradScaler("cuda")
|
| 273 |
+
|
| 274 |
+
steps_per_epoch = math.ceil(len(train_loader) / GRAD_ACCUM)
|
| 275 |
+
total_steps = steps_per_epoch * EPOCHS
|
| 276 |
+
|
| 277 |
+
def lr_at(step: int) -> float:
|
| 278 |
+
if step < WARMUP_STEPS:
|
| 279 |
+
return step / max(WARMUP_STEPS, 1)
|
| 280 |
+
progress = (step - WARMUP_STEPS) / max(total_steps - WARMUP_STEPS, 1)
|
| 281 |
+
return 0.5 * (1.0 + math.cos(math.pi * min(progress, 1.0)))
|
| 282 |
+
|
| 283 |
+
schedule = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_at)
|
| 284 |
+
|
| 285 |
+
step, start_epoch = 0, 0
|
| 286 |
+
if RESUME_FROM:
|
| 287 |
+
step, start_epoch = load_checkpoint(unet, optimizer, scaler, device)
|
| 288 |
+
for _ in range(step):
|
| 289 |
+
schedule.step()
|
| 290 |
+
|
| 291 |
+
# MODEL_REPO is created ahead of time, with its card, rather than by the
|
| 292 |
+
# job. A run that dies early should not leave an empty repo behind.
|
| 293 |
+
api = HfApi()
|
| 294 |
+
|
| 295 |
+
empty_tokens = tokenizer(
|
| 296 |
+
[""], padding="max_length", truncation=True,
|
| 297 |
+
max_length=tokenizer.model_max_length, return_tensors="pt",
|
| 298 |
+
).input_ids.to(device)
|
| 299 |
+
|
| 300 |
+
print(f"\n{total_steps:,} optimizer steps over {EPOCHS} epochs "
|
| 301 |
+
f"({steps_per_epoch:,}/epoch, effective batch "
|
| 302 |
+
f"{BATCH_SIZE * GRAD_ACCUM})\n")
|
| 303 |
+
|
| 304 |
+
unet.train()
|
| 305 |
+
for epoch in range(start_epoch, EPOCHS):
|
| 306 |
+
running, seen = 0.0, 0
|
| 307 |
+
|
| 308 |
+
for index, batch in enumerate(train_loader):
|
| 309 |
+
mean = batch["mean"].to(device, torch.float32)
|
| 310 |
+
logvar = batch["logvar"].to(device, torch.float32)
|
| 311 |
+
latents = sample_posterior(mean, logvar) * scaling_factor
|
| 312 |
+
|
| 313 |
+
noise = torch.randn_like(latents)
|
| 314 |
+
steps = torch.randint(
|
| 315 |
+
0, scheduler.config.num_train_timesteps,
|
| 316 |
+
(latents.shape[0],), device=device,
|
| 317 |
+
)
|
| 318 |
+
noisy = scheduler.add_noise(latents, noise, steps)
|
| 319 |
+
|
| 320 |
+
prompts = [
|
| 321 |
+
"" if random.random() < CAPTION_DROPOUT else p
|
| 322 |
+
for p in batch["prompt"]
|
| 323 |
+
]
|
| 324 |
+
tokens = tokenizer(
|
| 325 |
+
prompts, padding="max_length", truncation=True,
|
| 326 |
+
max_length=tokenizer.model_max_length, return_tensors="pt",
|
| 327 |
+
).input_ids.to(device)
|
| 328 |
+
with torch.no_grad():
|
| 329 |
+
encoded = text_encoder(tokens)[0]
|
| 330 |
+
|
| 331 |
+
with torch.autocast("cuda", dtype=dtype):
|
| 332 |
+
predicted = unet(noisy, steps, encoded).sample
|
| 333 |
+
# SD 1.5 is an epsilon-prediction model: the target is the
|
| 334 |
+
# noise itself, not the clean latent.
|
| 335 |
+
loss = F.mse_loss(predicted.float(), noise.float())
|
| 336 |
+
|
| 337 |
+
scaler.scale(loss / GRAD_ACCUM).backward()
|
| 338 |
+
running += loss.item()
|
| 339 |
+
seen += 1
|
| 340 |
+
|
| 341 |
+
if (index + 1) % GRAD_ACCUM == 0:
|
| 342 |
+
scaler.unscale_(optimizer)
|
| 343 |
+
torch.nn.utils.clip_grad_norm_(trainable, MAX_GRAD_NORM)
|
| 344 |
+
scaler.step(optimizer)
|
| 345 |
+
scaler.update()
|
| 346 |
+
optimizer.zero_grad(set_to_none=True)
|
| 347 |
+
schedule.step()
|
| 348 |
+
step += 1
|
| 349 |
+
|
| 350 |
+
if step % 50 == 0:
|
| 351 |
+
print(f" epoch {epoch} step {step}/{total_steps} "
|
| 352 |
+
f"loss {running / max(seen, 1):.4f} "
|
| 353 |
+
f"lr {schedule.get_last_lr()[0]:.2e}", flush=True)
|
| 354 |
+
running, seen = 0.0, 0
|
| 355 |
+
|
| 356 |
+
if step % CHECKPOINT_EVERY == 0:
|
| 357 |
+
save_checkpoint(unet, optimizer, scaler, step, epoch,
|
| 358 |
+
api, scaling_factor)
|
| 359 |
+
|
| 360 |
+
loss = validation_loss(unet, text_encoder, tokenizer, scheduler,
|
| 361 |
+
val_loader, device, dtype, scaling_factor)
|
| 362 |
+
print(f"epoch {epoch} complete - validation loss {loss:.4f}", flush=True)
|
| 363 |
+
|
| 364 |
+
save_checkpoint(unet, optimizer, scaler, step, EPOCHS - 1, api, scaling_factor)
|
| 365 |
+
print(f"\nDone. https://huggingface.co/{MODEL_REPO}")
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
if __name__ == "__main__":
|
| 369 |
+
main()
|