Datasets:
File size: 12,213 Bytes
3127b61 | 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 | # Copyright 2026 Jayce-Ping
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations.
"""Generate independent PolyText PNGs with Qwen-Image or FLUX and optional PEFT LoRA."""
import argparse
import fcntl
import json
import os
import re
import time
import zlib
from pathlib import Path
from typing import Any, Dict, List
import torch
from diffusers import DiffusionPipeline
from peft import PeftModel
from PIL import Image
DEFAULT_PROMPTS = Path(__file__).resolve().parent
SPLIT_FILES = (
"critical_en.jsonl",
"optional_en.jsonl",
"critical_zh.jsonl",
"optional_zh.jsonl",
)
def read_jsonl(path: Path) -> List[Dict[str, Any]]:
"""Read nonempty JSONL records."""
return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
def prompt_key(row: Dict[str, Any]) -> str:
"""Return the collision-free pair/task key."""
pair = row.get("pair_id")
task = row.get("task_type")
if not isinstance(pair, str) or not re.fullmatch(r"[A-Za-z0-9_-]+", pair):
raise ValueError(f"Invalid pair_id: {pair!r}")
if task not in ("critical", "optional"):
raise ValueError(f"Invalid task_type: {task!r}")
return f"{pair}_{task}"
def load_prompts(path: Path, mode: str) -> List[Dict[str, Any]]:
"""Load and validate one language of benchmark prompts."""
if path.is_dir():
missing = [name for name in SPLIT_FILES if not (path / name).is_file()]
if missing:
raise FileNotFoundError(f"Prompt directory {path} is missing {missing}")
rows = [row for name in SPLIT_FILES for row in read_jsonl(path / name)]
else:
rows = read_jsonl(path)
selected = []
seen = set()
for row in rows:
key = prompt_key(row)
if key in seen:
raise ValueError(f"Duplicate prompt ID: {key}")
seen.add(key)
if row.get("language") not in ("en", "zh"):
raise ValueError(f"Invalid language for {key}: {row.get('language')!r}")
targets = row.get("target_list")
if not isinstance(targets, list) or any(
not isinstance(target, str) or not target.strip() for target in targets
):
raise ValueError(f"Invalid target_list for {key}: {targets!r}")
if bool(targets) != (row["task_type"] == "critical"):
raise ValueError(f"Target/task mismatch for {key}")
if not isinstance(row.get("prompt"), str) or not row["prompt"].strip():
raise ValueError(f"Empty prompt for {key}")
if row["language"] == mode.lower():
selected.append(row)
if not selected:
raise ValueError(f"No prompts for mode={mode} in {path}")
return selected
def make_seed(row: Dict[str, Any], repeat: int) -> int:
"""Return the deterministic paired seed for one repeat."""
return zlib.crc32(f"{row['pair_id']}_{repeat}".encode()) & 0xFFFFFFFF
def image_complete(path: Path, width: int, height: int) -> bool:
"""Return whether an image decodes at the required resolution."""
try:
with Image.open(path) as image:
image.load()
return image.size == (width, height)
except (OSError, ValueError):
return False
def image_jobs(rows: List[Dict[str, Any]], image_dir: Path, repeats: int) -> List[Dict[str, Any]]:
"""Enumerate expected output images."""
return [
dict(
row=row,
repeat=repeat,
key=f"{prompt_key(row)}_{repeat}",
path=image_dir / f"{prompt_key(row)}_{repeat}.png",
)
for row in rows
for repeat in range(1, repeats + 1)
]
def shard_jobs(
jobs: List[Dict[str, Any]],
task_type: str,
node_index: int,
num_nodes: int,
rank: int,
world_size: int,
) -> List[Dict[str, Any]]:
"""Partition jobs across nodes and local workers without padding."""
if num_nodes < 1 or not 0 <= node_index < num_nodes:
raise ValueError(f"Expected 0 <= node_index({node_index}) < num_nodes({num_nodes})")
if world_size < 1 or not 0 <= rank < world_size:
raise ValueError(f"Expected 0 <= rank({rank}) < world_size({world_size})")
selected = [job for job in jobs if task_type == "all" or job["row"]["task_type"] == task_type]
return selected[node_index::num_nodes][rank::world_size]
def atomic_json(path: Path, value: Any) -> None:
"""Write JSON atomically."""
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n")
temporary.replace(path)
def main() -> None:
"""Run disjoint torchrun workers without padding or inter-rank collectives."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model-family", choices=["qwen", "flux"], required=True)
parser.add_argument("--mode", choices=["EN", "ZH"], default="EN")
parser.add_argument("--model_name", required=True)
parser.add_argument("--model_path", required=True)
parser.add_argument("--ckpt_path")
parser.add_argument("--gallery_output_dir", type=Path, required=True)
parser.add_argument("--negative_prompt", default=None)
parser.add_argument("--width", type=int, default=1024)
parser.add_argument("--height", type=int, default=1024)
parser.add_argument("--steps", type=int, default=50)
parser.add_argument("--repeats", type=int, default=4)
parser.add_argument("--prompts", type=Path, default=DEFAULT_PROMPTS)
parser.add_argument("--limit-prompts", type=int)
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--task-type", choices=["all", "critical", "optional"], default="all")
parser.add_argument("--node-index", type=int, default=0)
parser.add_argument("--num-nodes", type=int, default=1)
parser.add_argument("--progress-dir", type=Path)
args = parser.parse_args()
if min(args.width, args.height, args.steps, args.repeats) <= 0:
parser.error("Dimensions, steps and repeats must be positive")
if args.limit_prompts is not None and args.limit_prompts <= 0:
parser.error("limit-prompts must be positive")
rows = load_prompts(args.prompts, args.mode)
if args.limit_prompts:
rows = rows[: args.limit_prompts]
output = args.gallery_output_dir / f"{args.model_name}_{args.mode}"
jobs = image_jobs(rows, output, args.repeats)
rank, world = int(os.environ.get("RANK", 0)), int(os.environ.get("WORLD_SIZE", 1))
local_rank = int(os.environ.get("LOCAL_RANK", 0))
owned = shard_jobs(jobs, args.task_type, args.node_index, args.num_nodes, rank, world)
if args.dry_run:
print(
json.dumps(
dict(
output=str(output),
expected=len(jobs),
rank=rank,
owned=len(owned),
first=str(owned[0]["path"]) if owned else None,
)
)
)
return
adapter = None
if args.ckpt_path and args.ckpt_path != "None":
adapter = Path(args.ckpt_path)
if adapter.is_file():
adapter = adapter.parent
if (
not (adapter / "adapter_config.json").is_file()
or not (adapter / "adapter_model.safetensors").is_file()
):
raise FileNotFoundError(f"Incomplete PEFT adapter: {adapter}")
negative = args.negative_prompt
if negative in (None, "", "None"):
negative = " " if args.model_family == "qwen" else None
protocol = dict(
version=1,
prompts=rows,
model_path=args.model_path,
adapter=str(adapter.resolve()) if adapter else None,
adapter_stat=(
(adapter / "adapter_model.safetensors").stat().st_mtime_ns if adapter else None
),
model_family=args.model_family,
width=args.width,
height=args.height,
steps=args.steps,
repeats=args.repeats,
negative_prompt=negative,
guidance=4.0 if args.model_family == "qwen" else 3.5,
seeds=(
"explicit_prompt_seeds_or_crc32(pair_id_repeat)"
if any("seeds" in row for row in rows)
else "crc32(pair_id_repeat)"
),
)
output.mkdir(parents=True, exist_ok=True)
with (output / ".generation.lock").open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
manifest = output / "generation.json"
if manifest.exists():
if json.loads(manifest.read_text()) != protocol:
raise ValueError("Generation settings changed; choose a new model/output directory")
elif any(output.glob("*.png")):
raise ValueError("Existing images lack generation provenance; choose a fresh directory")
else:
atomic_json(manifest, protocol)
pending = [job for job in owned if not image_complete(job["path"], args.width, args.height)]
initial_done = len(owned) - len(pending)
durations = []
started_at = time.time()
def report(state: str, completed: int) -> None:
if args.progress_dir:
remaining = len(owned) - completed
seconds_per_image = sum(durations[-8:]) / len(durations[-8:]) if durations else None
atomic_json(
args.progress_dir / f"rank-{rank}.json",
dict(
rank=rank,
pid=os.getpid(),
observed_at=time.time(),
started_at=started_at,
state=state,
done=completed,
total=len(owned),
initial_done=initial_done,
eta_sec=(
remaining * seconds_per_image if seconds_per_image is not None else None
),
seconds_per_image=seconds_per_image,
task_type=args.task_type,
node_index=args.node_index,
num_nodes=args.num_nodes,
),
)
report("loading", initial_done)
if not pending:
report("done", len(owned))
print(f"Rank {rank}: all assigned images complete")
return
device = torch.device("cuda", local_rank)
torch.cuda.set_device(device)
pipe = DiffusionPipeline.from_pretrained(args.model_path, torch_dtype=torch.bfloat16).to(device)
pipe.set_progress_bar_config(disable=True)
if adapter:
pipe.transformer = PeftModel.from_pretrained(pipe.transformer, str(adapter))
pipe.transformer.eval()
kwargs = dict(width=args.width, height=args.height, num_inference_steps=args.steps)
if args.model_family == "qwen":
kwargs.update(negative_prompt=negative, true_cfg_scale=4.0)
else:
kwargs.update(guidance_scale=3.5)
if negative is not None:
kwargs.update(negative_prompt=negative, true_cfg_scale=4.0)
for index, job in enumerate(pending):
image_started = time.monotonic()
with torch.inference_mode():
image = pipe(
prompt=job["row"]["prompt"],
generator=torch.Generator(device=device).manual_seed(
make_seed(job["row"], job["repeat"])
),
**kwargs,
).images[0]
tmp = job["path"].with_name(f".{job['key']}.{os.getpid()}.tmp")
image.save(tmp, format="PNG")
tmp.replace(job["path"])
durations.append(time.monotonic() - image_started)
report("generating", initial_done + index + 1)
print(f"Rank {rank}: {index + 1}/{len(pending)} {job['path']}", flush=True)
report("done", len(owned))
if __name__ == "__main__":
main()
|