Spaces:
Running on Zero
Running on Zero
File size: 5,064 Bytes
dacd0ba | 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 | """Real empty-prompt generation and independent image-feedback experiments."""
import argparse
import json
import os
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parent
os.environ.setdefault("HF_HOME", str(ROOT / ".model-cache"))
os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS_WARNING", "1")
import numpy as np
import torch
from diffusers import AutoPipelineForImage2Image, AutoPipelineForText2Image
from huggingface_hub import model_info
from PIL import Image, ImageDraw
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", default="stabilityai/sd-turbo")
parser.add_argument("--seeds", nargs="+", type=int, default=[42, 31415])
parser.add_argument("--strengths", nargs="+", type=float, default=[0.25, 0.5, 0.75])
parser.add_argument("--cycles", type=int, default=6)
parser.add_argument("--output", type=Path, default=ROOT / "outputs" / "empty-prompt")
args = parser.parse_args()
if args.cycles < 1 or any(not 0.25 <= s <= 1 for s in args.strengths):
parser.error("cycles must be positive; strengths must be between .25 and 1 (4-step schedule)")
if not torch.cuda.is_available():
raise RuntimeError("CUDA PyTorch is required for this GPU experiment.")
args.output.mkdir(parents=True, exist_ok=True)
revision = model_info(args.model, token=False).sha
report = dict(model=args.model, revision=revision, prompt="", guidance_scale=0.0,
size=[512, 512], steps=4, cycles=args.cycles, torch=torch.__version__,
gpu=torch.cuda.get_device_name(), runs=[])
print(f"Loading {args.model}@{revision}; prompt is exactly an empty string", flush=True)
pipe = AutoPipelineForText2Image.from_pretrained(
args.model, revision=revision, torch_dtype=torch.float16, variant="fp16",
use_safetensors=True, token=False)
pipe.enable_model_cpu_offload()
feedback = AutoPipelineForImage2Image.from_pipe(pipe)
# Both wrappers share components and their offload hooks; no second model allocation.
torch.cuda.reset_peak_memory_stats()
tiles = []
def generate(pipeline, seed, **kwargs):
torch.cuda.synchronize()
start = time.perf_counter()
with torch.inference_mode():
result = pipeline(prompt="", guidance_scale=0.0, num_inference_steps=4,
generator=torch.Generator("cpu").manual_seed(seed), **kwargs)
torch.cuda.synchronize()
return result.images[0], round(time.perf_counter() - start, 3), getattr(result, "nsfw_content_detected", None)
for seed in args.seeds:
initial, seconds, flagged = generate(pipe, seed, height=512, width=512)
initial.save(args.output / f"seed-{seed}-initial.png")
report["runs"].append(dict(seed=seed, frame=0, seconds=seconds, safety_flags=flagged))
for strength in args.strengths:
current = initial.copy()
frames = [current]
row = [(current, f"seed {seed} | initial")]
for cycle in range(1, args.cycles + 1):
noise_seed = seed + cycle
previous = np.asarray(current, dtype=np.float32)
current, seconds, flagged = generate(feedback, noise_seed, image=current, strength=strength)
pixels = np.asarray(current, dtype=np.float32)
entry = dict(seed=seed, noise_seed=noise_seed, strength=strength, frame=cycle,
seconds=seconds, mean_absolute_change=float(np.abs(pixels-previous).mean()/255),
pixel_std=float(pixels.std()), safety_flags=flagged)
report["runs"].append(entry)
name = f"seed-{seed}-drift-{strength:g}-frame-{cycle:02d}.png"
current.save(args.output / name)
frames.append(current)
row.append((current, f"drift {strength:g} | frame {cycle}"))
print(json.dumps(entry), flush=True)
(args.output / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
frames[0].save(args.output / f"seed-{seed}-drift-{strength:g}.gif",
save_all=True, append_images=frames[1:], duration=700, loop=0)
tiles.append(row)
sheet = Image.new("RGB", (len(tiles[0])*192, len(tiles)*216), "#171a20")
draw = ImageDraw.Draw(sheet)
for y, row in enumerate(tiles):
for x, (frame, label) in enumerate(row):
sheet.paste(frame.resize((192,192)), (x*192, y*216))
draw.text((x*192+5, y*216+196), label, fill="white")
sheet.save(args.output / "contact-sheet.jpg")
report["peak_allocated_gb"] = torch.cuda.max_memory_allocated()/1024**3
report["peak_reserved_gb"] = torch.cuda.max_memory_reserved()/1024**3
(args.output / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
print(f"Done: {args.output}; peak allocated {report['peak_allocated_gb']:.2f} GiB", flush=True)
if __name__ == "__main__":
main()
|