Instructions to use PrunaAI/P-Flux-2-Klein-4B-DWD with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Pruna AI
How to use PrunaAI/P-Flux-2-Klein-4B-DWD with Pruna AI:
from pruna import PrunaModel model = PrunaModel.from_pretrained("PrunaAI/P-Flux-2-Klein-4B-DWD") - Notebooks
- Google Colab
- Kaggle
File size: 8,381 Bytes
24baf68 | 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 | """Train the DWD tail + pixel head on FLUX.2 [klein] 4B. One process per GPU, launched with torchrun:
torchrun --standalone --nproc_per_node 8 scripts/train.py --run-name my-run --data-root ./data
The defaults are the full recipe (26k iterations, global batch 128, discriminator from 2500, adversarial loss from
3000). The global batch must be a multiple of micro-batch x number of GPUs; the rest is gradient accumulation.
A run resumes automatically from <ckpt-root>/<run-name>/latest. Without a checkpoint it first fits the DWD head by
least squares (--lsq-images real images at t ~ p_pix) and saves ckpt_000000.pt (the untrained-head baseline), unless
--init-from takes the student from another run's ckpt_000000.pt.
Exit status: 0 finished; 3 stopped early by SIGTERM / SIGINT or --max-hours after writing a checkpoint (run the same
command again to resume); 4 aborted after --max-bad-steps consecutive non-finite steps (no checkpoint written).
torchrun reports any worker failure as 1, so <ckpt-root>/<run-name>/exit_status.json also records the reason.
Use --run-name, not --run: torchrun abbreviation-matches "--run" against its own --run-path option.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from dataclasses import fields
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "src"))
import torch # noqa: E402
import torch.distributed as dist # noqa: E402
from dwd_klein.trainer import Config, NonFiniteAbort, Trainer # noqa: E402
EXIT_RESUMABLE = 3 # stopped early by a signal or the --max-hours deadline after a checkpoint: run again to resume
EXIT_NONFINITE = 4 # aborted after --max-bad-steps consecutive non-finite steps: do not retry blindly
def parse(argv=None) -> Config:
d = Config()
p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
p.add_argument("--run-name", dest="run", default=d.run, help="run directory name under --ckpt-root")
p.add_argument("--ckpt-root", default=d.ckpt_root)
p.add_argument("--data-root", default=d.data_root, help="tar-shard dataset root (docs/data_format.md)")
p.add_argument("--model-path", default=d.model_path, help="Hugging Face repo id or local diffusers directory")
p.add_argument("--dino-path", default=d.dino_path,
help="local DINO ViT-S/8 model.safetensors for the discriminator (empty: download it)")
p.add_argument("--k", type=int, default=d.k, help="number of adapted single blocks")
p.add_argument("--iters", type=int, default=d.iters)
p.add_argument("--d-start", type=int, default=d.d_start, help="iteration at which the discriminator starts")
p.add_argument("--adv-start", type=int, default=d.adv_start, help="iteration at which the adversarial loss starts")
p.add_argument("--global-batch", type=int, default=d.global_batch)
p.add_argument("--micro-batch", type=int, default=d.micro_batch, help="per GPU and accumulation step")
p.add_argument("--split-batch", action="store_true", help="P=1: half the micro-batch per loss branch")
p.add_argument("--no-grad-ckpt", action="store_true",
help="disable activation checkpointing on the adapted blocks (on by default)")
p.add_argument("--lr", type=float, default=d.lr)
p.add_argument("--head-lr-mult", type=float, default=d.head_lr_mult)
p.add_argument("--warmup", type=int, default=d.warmup)
p.add_argument("--clip", type=float, default=d.clip, help="generator gradient-norm clip")
p.add_argument("--lambda-traj", type=float, default=d.lambda_traj)
p.add_argument("--adv-scale", type=float, default=d.adv_scale, help="multiplier on the adaptive adversarial weight")
p.add_argument("--d-lr", type=float, default=d.d_lr)
p.add_argument("--crops", type=int, default=d.crops, help="discriminator crops per image")
p.add_argument("--crop-size", type=int, default=d.crop_size)
p.add_argument("--ema-gamma", type=float, default=d.ema_gamma)
p.add_argument("--ema-start", type=int, default=d.ema_start)
p.add_argument("--ckpt-every", type=int, default=d.ckpt_every)
p.add_argument("--keep", type=int, default=d.keep, help="number of recent checkpoints kept (plus ckpt_000000)")
p.add_argument("--keep-every", type=int, default=d.keep_every,
help="also never prune checkpoints at multiples of this iteration (0: off)")
p.add_argument("--log-every", type=int, default=d.log_every)
p.add_argument("--lsq-images", type=int, default=d.lsq_images, help="images for the least-squares head init")
p.add_argument("--seed", type=int, default=d.seed)
p.add_argument("--buckets", default="", help="comma list; default: every bucket with train shards")
p.add_argument("--bucket-weights", default="", help='JSON {"1024x1024": 2.0, ...}; default: sample counts')
p.add_argument("--max-hours", type=float, default=d.max_hours,
help="stop gracefully (checkpoint, exit 3) after this many hours (0: no limit)")
p.add_argument("--max-bad-steps", type=int, default=d.max_bad_steps,
help="abort (exit 4, no checkpoint) after this many consecutive non-finite generator steps")
p.add_argument("--init-from", default=d.init_from,
help="fresh run: load the student (LSQ head) from this iteration-0 checkpoint, skip the LSQ fit")
p.add_argument("--smoke", action="store_true",
help="quick end-to-end check: 20 iterations, D from 5, adversarial loss from 10, ckpt every 10")
a = p.parse_args(argv)
cfg = Config(run=a.run, ckpt_root=a.ckpt_root, data_root=a.data_root, model_path=a.model_path,
dino_path=a.dino_path, k=a.k, iters=a.iters, d_start=a.d_start, adv_start=a.adv_start,
global_batch=a.global_batch, micro_batch=a.micro_batch, split_batch=a.split_batch,
grad_ckpt=not a.no_grad_ckpt, lr=a.lr, head_lr_mult=a.head_lr_mult, warmup=a.warmup, clip=a.clip,
lambda_traj=a.lambda_traj, adv_scale=a.adv_scale, d_lr=a.d_lr, crops=a.crops,
crop_size=a.crop_size, ema_gamma=a.ema_gamma, ema_start=a.ema_start, ckpt_every=a.ckpt_every,
keep=a.keep, keep_every=a.keep_every, log_every=a.log_every, lsq_images=a.lsq_images, seed=a.seed,
buckets=[b for b in a.buckets.split(",") if b],
bucket_weights=json.loads(a.bucket_weights) if a.bucket_weights else {},
max_hours=a.max_hours, max_bad_steps=a.max_bad_steps, init_from=a.init_from)
if a.smoke:
cfg.iters, cfg.d_start, cfg.adv_start = 20, 5, 10
cfg.ckpt_every, cfg.log_every, cfg.warmup, cfg.ema_start = 10, 1, 5, 5
cfg.lsq_images = min(cfg.lsq_images, 256)
return cfg
def main(argv=None):
cfg = parse(argv)
if not torch.cuda.is_available():
raise SystemExit("training needs CUDA GPUs")
world = int(os.environ.get("WORLD_SIZE", "1"))
rank = int(os.environ.get("RANK", "0"))
local = int(os.environ.get("LOCAL_RANK", "0"))
torch.cuda.set_device(local)
dev = torch.device("cuda", local)
if world > 1:
dist.init_process_group("nccl", device_id=dev)
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
torch.manual_seed(cfg.seed + rank)
torch.cuda.manual_seed(cfg.seed + rank)
def log(msg):
print(f"[r{rank}] {msg}" if rank else msg, flush=True)
from dwd_klein.build import build_components
if rank == 0:
log("CONFIG " + json.dumps({f.name: getattr(cfg, f.name) for f in fields(cfg)}, default=str))
comps, _ = build_components(cfg, dev, rank, world)
tr = Trainer(cfg, comps, dev, log=log if rank == 0 else (lambda m: None))
log(f"BUILD done: accum={tr.accum} mem={torch.cuda.memory_allocated(dev) / 2**30:.1f} GiB")
code = 0
try:
it = tr.fit()
log(f"EXIT it={it} reason={tr.stop_reason}")
if tr.stop_reason in ("signal", "deadline"):
code = EXIT_RESUMABLE
except NonFiniteAbort as e:
log(f"ABORT {e}")
code = EXIT_NONFINITE
if world > 1 and code != EXIT_NONFINITE:
dist.destroy_process_group()
return code
if __name__ == "__main__":
sys.exit(main())
|