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.
johnrachwanpruna's picture
P-Flux-2-Klein-4B-DWD
24baf68
Raw History Blame Contribute Delete
17.5 kB
"""Bucketed tar-shard loader (WebDataset layout) with exact resume.
<root>/manifest.json optional shard list: shards[{path, split, bucket, count}], totals
<root>/<split>/<bucket>/*.tar split = train | val, bucket = "<W>x<H>" (e.g. 1152x896)
members <key>.jpg|.jpeg|.png|.webp (image), <key>.txt (caption), <key>.json (optional metadata)
Without a manifest the shards are globbed. Images whose size differs from the bucket's are resized to cover it and
center-cropped (a no-op when the shards already hold images of exactly the bucket size). The optional json may hold
"captions" (a list of alternative captions; one is picked per sample and epoch) and "source" (a label used only to
stratify the validation subset). docs/data_format.md describes the format.
Determinism / resume:
- the bucket of (step, micro) is drawn from np.random.default_rng([seed, step, micro]) with weights proportional to
each bucket's train sample count (manifest) or shard count, so every rank uses the same bucket in a step (same
sequence length on every GPU);
- each rank streams its own shards of a bucket (shards[rank::world]; if a bucket has fewer shards than ranks, every
rank reads all of them and keeps samples p % world == rank). Shards are taken in a per-epoch permutation, in
groups of `group` shards (default 4, so one micro-batch mixes several shards), and the samples of a group are
permuted, all seeded by (seed, crc32(bucket), epoch[, group]);
- a sample with several captions uses one of them, picked by (seed, crc32(key), epoch);
- a sample that fails to decode (or a shard that fails to read, after one retry) is logged and skipped; the stream
simply moves on, so the skip is deterministic and resume stays exact;
- the next shard group of a bucket is read ahead in a background thread (same bytes, so resume is unaffected);
- the stream state (epoch, group position, sample position) per bucket is a few ints. A background thread
prefetches batches; each batch carries the loader state right after it, and the trainer checkpoints the state
of the last batch it consumed, so prefetched batches are re-produced after a resume.
"""
from __future__ import annotations
import glob
import io
import math
import os
import queue
import tarfile
import threading
import zlib
from dataclasses import dataclass
import numpy as np
import torch
IMG_EXT = ("jpg", "jpeg", "png", "webp")
MAX_BAD_PER_BATCH = 64 # more undecodable samples than this while filling one micro-batch: the data is broken, raise
def _warn(msg: str):
print(f"DATA_WARN {msg}", flush=True)
def parse_bucket(name: str) -> tuple[int, int]:
"""'1152x896' -> (width 1152, height 896)."""
w, h = name.lower().split("x")
return int(w), int(h)
def read_shard(path: str) -> list[dict]:
"""All samples of one tar, in file order: [{key, img (bytes), txt, json}]. Samples without an image are dropped;
a sample without a .txt takes json.caption or json.prompt."""
import json
samples: dict[str, dict] = {}
order = []
with tarfile.open(path, "r") as tf:
for m in tf:
if not m.isfile():
continue
d, base = os.path.split(m.name)
if "." not in base:
continue
stem, ext = base.split(".", 1)
key = os.path.join(d, stem)
ext = ext.lower()
data = tf.extractfile(m).read()
s = samples.get(key)
if s is None:
s = samples[key] = {"key": key}
order.append(key)
if ext in IMG_EXT:
s["img"] = data
elif ext == "txt":
s["txt"] = data.decode("utf-8").strip()
elif ext == "json":
s["json"] = json.loads(data)
out = []
for k in order:
s = samples[k]
if "img" not in s:
continue
if "txt" not in s:
j = s.get("json") or {}
s["txt"] = str(j.get("caption", j.get("prompt", "")))
out.append(s)
return out
def decode_image(data: bytes, size: tuple[int, int]) -> torch.Tensor:
"""bytes -> uint8 [3, H, W] at size (W, H): resize to cover, then center crop."""
from PIL import Image
im = Image.open(io.BytesIO(data))
im = im.convert("RGB")
W, H = size
if im.size != (W, H):
s = max(W / im.width, H / im.height)
nw, nh = max(W, round(im.width * s)), max(H, round(im.height * s))
im = im.resize((nw, nh), Image.BICUBIC)
l, t = (nw - W) // 2, (nh - H) // 2
im = im.crop((l, t, l + W, t + H))
return torch.from_numpy(np.asarray(im, dtype=np.uint8).copy()).permute(2, 0, 1).contiguous()
from concurrent.futures import ThreadPoolExecutor as _TPE # noqa: E402
_AHEAD_POOL = _TPE(max_workers=2, thread_name_prefix="dwd-readahead") # reads the next shard groups
class BucketStream:
def __init__(self, bucket: str, shards: list[str], seed: int, stride: tuple[int, int] = (0, 1), group: int = 4,
read_ahead: bool = True):
assert shards, f"no shards for bucket {bucket}"
self.bucket, self.shards, self.seed, self.stride = bucket, list(shards), seed, stride
self.group = max(1, min(group, len(self.shards)))
self.n_groups = math.ceil(len(self.shards) / self.group)
self.tag = zlib.crc32(bucket.encode())
self.epoch = self.group_pos = self.sample_pos = 0
self._cache_key = None
self._cache = None
self._ahead: tuple | None = None # (key, Future of the raw samples of the next group)
self.read_ahead = read_ahead
def _group_paths(self, epoch: int, group_pos: int) -> list[str]:
order = np.random.default_rng([self.seed, self.tag, epoch]).permutation(len(self.shards)).tolist()
return [self.shards[si] for si in order[group_pos * self.group:(group_pos + 1) * self.group]]
def _read_group(self, paths: list[str]) -> list[dict]:
"""The group's shards, read in parallel (a cold network read of one shard is I/O-bound), in group order."""
if len(paths) == 1:
return self._read(paths[0])
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(len(paths)) as ex:
return [s for part in ex.map(self._read, paths) for s in part]
def _next_key(self, key: tuple) -> tuple:
e, g = key
return (e, g + 1) if g + 1 < self.n_groups else (e + 1, 0)
def _load(self):
key = (self.epoch, self.group_pos)
if self._cache_key != key:
if self._ahead is not None and self._ahead[0] == key:
samples = self._ahead[1].result()
else:
samples = self._read_group(self._group_paths(*key))
self._ahead = None
perm = np.random.default_rng([self.seed, self.tag, self.epoch, 1 + self.group_pos]) \
.permutation(len(samples)).tolist()
off, k = self.stride
perm = [p for j, p in enumerate(perm) if j % k == off]
self._cache_key, self._cache = key, [samples[p] for p in perm]
if self.read_ahead and self.n_groups > 1:
# read the next group in the background while this one is consumed (same bytes either way, so resume
# stays exact)
nk = self._next_key(key)
self._ahead = (nk, _AHEAD_POOL.submit(self._read_group, self._group_paths(*nk)))
return self._cache
@staticmethod
def _read(path: str) -> list[dict]:
for attempt in (0, 1):
try:
return read_shard(path)
except Exception as e: # noqa: BLE001 - a corrupt / unreadable shard must not kill a multi-GPU run
_warn(f"shard {path} unreadable (attempt {attempt + 1}): {type(e).__name__}: {e}")
return []
def release(self):
self._cache_key = self._cache = None
if self._ahead is not None:
self._ahead[1].cancel()
self._ahead = None
def _caption(self, s: dict) -> str:
caps = (s.get("json") or {}).get("captions")
if isinstance(caps, list) and len(caps) > 1 and all(isinstance(c, str) and c for c in caps):
i = int(np.random.default_rng([self.seed, zlib.crc32(s["key"].encode()), self.epoch]).integers(len(caps)))
return caps[i].strip()
return s["txt"]
def next(self) -> dict:
for _ in range(self.n_groups * 2 + 2):
cur = self._load()
if self.sample_pos < len(cur):
s = cur[self.sample_pos]
self.sample_pos += 1
return {**s, "txt": self._caption(s)}
self.sample_pos = 0
self.group_pos += 1
if self.group_pos >= self.n_groups:
self.group_pos = 0
self.epoch += 1
raise RuntimeError(f"bucket {self.bucket}: no samples for this rank")
def state_dict(self) -> dict:
return {"epoch": self.epoch, "group_pos": self.group_pos, "sample_pos": self.sample_pos}
def load_state_dict(self, sd: dict):
self.epoch, self.group_pos, self.sample_pos = sd["epoch"], sd["group_pos"], sd["sample_pos"]
@dataclass
class Batch:
step: int
micro: int
bucket: str
images: torch.Tensor # uint8 [B, 3, H, W]
captions: list[str]
keys: list[str]
state: dict # loader state right after this batch
def list_buckets(root: str, split: str = "train") -> dict[str, list[str]]:
"""bucket -> sorted shard paths of `split` (manifest order when <root>/manifest.json exists)."""
import json
out: dict[str, list[str]] = {}
man = os.path.join(root, "manifest.json")
if os.path.exists(man):
with open(man) as fh:
m = json.load(fh)
for sh in m["shards"]:
if sh["split"] == split:
out.setdefault(sh["bucket"], []).append(os.path.join(root, sh["path"]))
return {b: out[b] for b in sorted(out)}
sub = os.path.join(root, split)
cands = [(d, os.path.join(sub, d)) for d in sorted(os.listdir(sub))] if os.path.isdir(sub) else []
for b, d in cands:
try:
parse_bucket(b)
except ValueError:
continue
shards = sorted(glob.glob(os.path.join(d, "*.tar")))
if shards:
out[b] = shards
return out
def bucket_counts(root: str, split: str = "train") -> dict[str, float]:
"""Sample count per bucket from the manifest ({} without one)."""
import json
man = os.path.join(root, "manifest.json")
if not os.path.exists(man):
return {}
with open(man) as fh:
tot = json.load(fh).get("totals", {}).get(split, {}).get("by_bucket", {})
return {b: float(v["count"]) for b, v in tot.items()}
class BucketLoader:
def __init__(self, root: str, micro_batch: int, rank: int = 0, world: int = 1, seed: int = 0,
split: str = "train", buckets: list[str] | None = None, weights: dict[str, float] | None = None,
prefetch: int = 8, group: int = 4):
allb = list_buckets(root, split)
if buckets:
allb = {b: allb[b] for b in buckets}
assert allb, f"no buckets with {split} shards under {root}"
self.names = sorted(allb)
counts = bucket_counts(root, split)
w = np.array([float((weights or {}).get(b, counts.get(b, len(allb[b])))) for b in self.names])
self.p = w / w.sum()
self.micro_batch, self.seed, self.rank, self.world = micro_batch, seed, rank, world
self.streams = {}
for b in self.names:
sh = allb[b]
if len(sh) >= world:
self.streams[b] = BucketStream(b, sh[rank::world], seed + 1000 * rank, group=group)
else:
self.streams[b] = BucketStream(b, sh, seed, stride=(rank, world), group=group)
self.prefetch = prefetch
self._q: queue.Queue | None = None
self._thread = None
self._stop = threading.Event()
self.n_bad = 0
def release(self):
"""Free the cached shard groups (the LSQ loader would otherwise keep one shard group per bucket in memory)."""
for st in self.streams.values():
st.release()
def bucket_for(self, step: int, micro: int) -> str:
return self.names[int(np.random.default_rng([self.seed, step, micro]).choice(len(self.names), p=self.p))]
def state_dict(self) -> dict:
return {b: s.state_dict() for b, s in self.streams.items()}
def load_state_dict(self, sd: dict):
for b, s in self.streams.items():
if b in sd:
s.load_state_dict(sd[b])
def _make(self, step: int, micro: int) -> Batch:
b = self.bucket_for(step, micro)
size = parse_bucket(b)
st = self.streams[b]
samples, imgs, bad = [], [], 0
while len(samples) < self.micro_batch:
s = st.next()
try:
im = decode_image(s["img"], size)
except Exception as e: # noqa: BLE001 - skip (deterministically) instead of crashing every rank's step
bad += 1
self.n_bad += 1
_warn(f"skip undecodable sample {s.get('key')} in {b}: {type(e).__name__}: {e} (total {self.n_bad})")
if bad > MAX_BAD_PER_BATCH:
raise RuntimeError(f"bucket {b}: {bad} undecodable samples while filling one micro-batch") from e
continue
samples.append(s)
imgs.append(im)
imgs = torch.stack(imgs)
if torch.cuda.is_available():
imgs = imgs.pin_memory()
return Batch(step, micro, b, imgs, [s["txt"] for s in samples], [s["key"] for s in samples],
self.state_dict())
# -- prefetch ------------------------------------------------------------------------------------------------
def start(self, step: int, accum: int):
"""Begin producing batches for (step, 0..accum-1), (step+1, ...) ... in a background thread."""
self.stop()
self._stop.clear()
self._q = queue.Queue(maxsize=self.prefetch)
def run():
s = step
try:
while not self._stop.is_set():
for m in range(accum):
item = self._make(s, m)
while not self._stop.is_set():
try:
self._q.put(item, timeout=0.5)
break
except queue.Full:
continue
s += 1
except BaseException as e: # noqa: BLE001 - surfaced in next()
self._q.put(e)
self._thread = threading.Thread(target=run, daemon=True, name="dwd-prefetch")
self._thread.start()
def next(self, step: int, micro: int) -> Batch:
item = self._q.get()
if isinstance(item, BaseException):
raise item
assert (item.step, item.micro) == (step, micro), (item.step, item.micro, step, micro)
return item
def stop(self):
if self._thread is not None:
self._stop.set()
while self._thread.is_alive():
try:
self._q.get_nowait()
except queue.Empty:
pass
self._thread.join(timeout=0.1)
self._thread = None
def sample_source(s: dict) -> str:
"""json.source if present, else the key prefix before the first '-'."""
src = (s.get("json") or {}).get("source")
return str(src) if src else os.path.basename(s["key"]).split("-", 1)[0]
def val_subset(root: str, n: int, seed: int = 0, buckets: list[str] | None = None) -> list[tuple]:
"""n held-out samples stratified by (source, bucket): every val sample is read, each stratum is shuffled with a
fixed seed, and strata are taken round-robin, so any prefix of the result covers the strata evenly (even when the
val shards hold one source after another).
Returns [(key, uint8 [3, H, W], caption, source, bucket)]."""
lb = list_buckets(root, "val")
strata: dict[tuple[str, str], list[dict]] = {}
for b in sorted(buckets or lb):
for sh in lb.get(b, []):
for s in read_shard(sh):
strata.setdefault((sample_source(s), b), []).append(s)
order = sorted(strata)
for i, k in enumerate(order):
perm = np.random.default_rng([seed, i]).permutation(len(strata[k])).tolist()
strata[k] = [strata[k][p] for p in perm]
out, depth = [], 0
while len(out) < n and any(depth < len(strata[k]) for k in order):
for k in order:
if depth < len(strata[k]) and len(out) < n:
s = strata[k][depth]
out.append((s["key"], decode_image(s["img"], parse_bucket(k[1])), s["txt"], k[0], k[1]))
depth += 1
return out
def iter_val(root: str, bucket: str, n: int):
"""First n samples of the bucket's val shards in manifest / file order (deterministic held-out set)."""
size = parse_bucket(bucket)
k = 0
for sh in list_buckets(root, "val").get(bucket, []):
for s in read_shard(sh):
if k >= n:
return
yield s["key"], decode_image(s["img"], size), s["txt"]
k += 1