4k-image-model-scripts / scripts /quality_check.py
memoryai's picture
Upload folder using huggingface_hub
1951446 verified
#!/usr/bin/env python3
"""
Auto quality check: generate full-quality 1024px samples, compare with previous step, upload to HF.
Run after each 2000-step checkpoint.
"""
import sys
import time
import json
import shutil
from pathlib import Path
import torch
import numpy as np
from PIL import Image
PROMPTS = [
"a beautiful mountain landscape at sunset, 4k, highly detailed, cinematic lighting",
"a cute cat sitting on a windowsill, natural lighting, sharp focus",
"a futuristic city skyline at night with neon lights, cyberpunk, ultra detailed",
"portrait of a woman with flowers in her hair, oil painting style, masterpiece",
]
CKPT_DIR = Path("/data0/checkpoints/flux_lora_train")
OUTPUT_DIR = Path("/data1/outputs/quality_check")
HISTORY_FILE = OUTPUT_DIR / "history.json"
def load_history():
if HISTORY_FILE.exists():
return json.loads(HISTORY_FILE.read_text())
return {}
def save_history(history):
HISTORY_FILE.write_text(json.dumps(history, indent=2))
def analyze_image(img):
arr = np.array(img).astype(float)
r, g, b = arr[:,:,0].mean(), arr[:,:,1].mean(), arr[:,:,2].mean()
std = arr.std()
gray = arr.mean(axis=2)
dx = np.diff(gray, axis=1)
dy = np.diff(gray, axis=0)
edge = (np.abs(dx).mean() + np.abs(dy).mean()) / 2
sat = (arr.max(axis=2) - arr.min(axis=2)).mean()
return {"std": round(std, 1), "edge": round(edge, 1), "sat": round(sat, 1), "rgb": f"({r:.0f},{g:.0f},{b:.0f})"}
def generate_full_quality(step):
from diffusers import FluxTransformer2DModel, FluxPipeline
from peft import LoraConfig, get_peft_model, set_peft_model_state_dict
import safetensors.torch
ckpt_path = CKPT_DIR / f"checkpoint-{step}" / "adapter_model.safetensors"
if not ckpt_path.exists():
print(f" Checkpoint {step} not found")
return None
print(f" Loading Flux Dev + LoRA (step {step})...")
transformer = FluxTransformer2DModel.from_pretrained(
"black-forest-labs/FLUX.1-dev", subfolder="transformer",
torch_dtype=torch.bfloat16, cache_dir="/data0/models",
)
lora_target_modules = [
"attn.to_q", "attn.to_k", "attn.to_v", "attn.to_out.0",
"attn.add_k_proj", "attn.add_q_proj", "attn.add_v_proj", "attn.to_add_out",
"ff.net.0.proj", "ff.net.2", "ff_context.net.0.proj", "ff_context.net.2",
]
lora_config = LoraConfig(r=128, lora_alpha=64, target_modules=lora_target_modules, lora_dropout=0.0)
transformer = get_peft_model(transformer, lora_config)
state_dict = safetensors.torch.load_file(str(ckpt_path))
set_peft_model_state_dict(transformer, state_dict)
transformer.eval()
pipe = FluxPipeline.from_pretrained(
"black-forest-labs/FLUX.1-dev", transformer=transformer,
torch_dtype=torch.bfloat16, cache_dir="/data0/models",
)
pipe = pipe.to("cuda:0")
step_dir = OUTPUT_DIR / f"step_{step}"
step_dir.mkdir(parents=True, exist_ok=True)
results = []
print(f" Generating 4 images (1024px, 28 steps, guidance 3.5)...")
for i, prompt in enumerate(PROMPTS):
image = pipe(prompt=prompt, num_inference_steps=28, guidance_scale=3.5, height=1024, width=1024).images[0]
image.save(step_dir / f"sample_{i}.png")
stats = analyze_image(image)
stats["prompt"] = prompt[:50]
results.append(stats)
print(f" Sample {i}: std={stats['std']}, sat={stats['sat']}, edge={stats['edge']}")
del pipe, transformer
torch.cuda.empty_cache()
return results
def compare_and_report(step, current_stats, history):
print(f"\n{'='*60}")
print(f" REPORT: Step {step}")
print(f"{'='*60}")
avg_std = np.mean([s["std"] for s in current_stats])
avg_edge = np.mean([s["edge"] for s in current_stats])
avg_sat = np.mean([s["sat"] for s in current_stats])
print(f" Avg std={avg_std:.1f}, edge={avg_edge:.1f}, sat={avg_sat:.1f}")
# Compare with previous
steps = sorted([int(k) for k in history.keys()])
if steps:
prev_step = steps[-1]
prev = history[str(prev_step)]
prev_avg_std = np.mean([s["std"] for s in prev["stats"]])
prev_avg_edge = np.mean([s["edge"] for s in prev["stats"]])
prev_avg_sat = np.mean([s["sat"] for s in prev["stats"]])
print(f"\n vs Step {prev_step}:")
print(f" Std: {prev_avg_std:.1f} β†’ {avg_std:.1f} {'↑' if avg_std > prev_avg_std else '↓'} ({avg_std-prev_avg_std:+.1f})")
print(f" Edge: {prev_avg_edge:.1f} β†’ {avg_edge:.1f} {'↑' if avg_edge > prev_avg_edge else '↓'} ({avg_edge-prev_avg_edge:+.1f})")
print(f" Sat: {prev_avg_sat:.1f} β†’ {avg_sat:.1f} {'↑' if avg_sat > prev_avg_sat else '↓'} ({avg_sat-prev_avg_sat:+.1f})")
# Verdict
if avg_sat > 40 and avg_std > 50 and avg_edge > 5:
verdict = "GOOD"
elif avg_sat > 30 and avg_std > 40:
verdict = "OK"
else:
verdict = "NEEDS MORE TRAINING"
print(f"\n Verdict: {verdict}")
print(f"{'='*60}\n")
return {"avg_std": avg_std, "avg_edge": avg_edge, "avg_sat": avg_sat, "verdict": verdict}
def upload_to_hf(step):
from huggingface_hub import upload_folder
token = open('/home/adminuser/.cache/huggingface/token').read().strip()
repo_id = "memoryai/4k-training-samples"
step_dir = OUTPUT_DIR / f"step_{step}"
print(f" Uploading step_{step} to HF...")
upload_folder(
folder_path=str(step_dir),
repo_id=repo_id,
path_in_repo=f"step_{step}_fullquality",
repo_type="dataset",
token=token,
)
print(f" Uploaded!")
def main():
step = int(sys.argv[1]) if len(sys.argv) > 1 else None
if step is None:
# Auto-detect latest checkpoint
checkpoints = sorted(
[d for d in CKPT_DIR.iterdir() if d.is_dir() and d.name.startswith("checkpoint-")],
key=lambda p: int(p.name.split("-")[1]),
)
if not checkpoints:
print("No checkpoints found")
return
step = int(checkpoints[-1].name.split("-")[1])
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
history = load_history()
# Skip if already done
if str(step) in history:
print(f" Step {step} already evaluated")
return
print(f"\n=== Quality Check: Step {step} ===")
t0 = time.time()
stats = generate_full_quality(step)
if stats is None:
return
summary = compare_and_report(step, stats, history)
# Save to history
history[str(step)] = {"stats": stats, "summary": summary, "time": time.strftime("%Y-%m-%d %H:%M")}
save_history(history)
# Upload
upload_to_hf(step)
print(f" Total time: {time.time()-t0:.0f}s")
if __name__ == "__main__":
main()