Run this model with HF Jobs
Run PrunaAI/P-Flux-2-Klein-4B-DWD on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/PrunaAI/P-Flux-2-Klein-4B-DWD. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/PrunaAI/P-Flux-2-Klein-4B-DWD on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
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
Download scripts/train.py from PrunaAI/P-Flux-2-Klein-4B-DWD: direct link, hf CLI and curl.
- Browser
- Download file 8.38 kB
-
https://huggingface.co/PrunaAI/P-Flux-2-Klein-4B-DWD/resolve/main/scripts/train.py
- Command line
-
hf download hf://PrunaAI/P-Flux-2-Klein-4B-DWD/scripts/train.py
-
curl -L -o train.py https://huggingface.co/PrunaAI/P-Flux-2-Klein-4B-DWD/resolve/main/scripts/train.py
8.38 kB
| """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()) | |