Spaces:
Running
Running
File size: 6,469 Bytes
2e175db | 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 | """
Generate synthetic images with Stable Diffusion 3.5 Medium.
License
-------
`stabilityai/stable-diffusion-3.5-medium` is available under the Stability AI
Community License. Stage 3A conditionally approved it while Veridicate remains
under the license revenue threshold and satisfies registration requirements.
Enterprise licensing is required before use above that threshold. Do not use
outputs to create or improve a foundational generative AI model. See
`NOTICES.md` before running a real generation job.
Usage
-----
python scripts/dataset/generate_sd35_synthetic.py \\
--out data/raw/ai_generated/sd35-medium \\
--count 20000 \\
--prompts scripts/dataset/prompts.txt
Dry run, no model import/download:
python scripts/dataset/generate_sd35_synthetic.py \\
--out data/raw/ai_generated/sd35-medium \\
--count 3 \\
--dry-run
Hardware
--------
SD 3.5 Medium generation should be run on a CUDA GPU with enough VRAM for
1024x1024 half-precision inference. Start with a small smoke run on the target
GPU before renting a long job.
Idempotency
-----------
Each generated file is named by a hash of (prompt, seed), so re-runs skip
already-generated images. Crash-resume works automatically.
"""
from __future__ import annotations
import argparse
import csv
import random
from pathlib import Path
from generation_utils import (
APPROVED_GENERATORS,
STAGE3A_MANIFEST_FIELDS,
choose_prompt,
image_dimensions,
infer_data_root,
load_prompts,
manifest_row,
next_seed,
sha256_file,
stable_image_key,
)
FALLBACK_PROMPTS = [
"a realistic phone photo of a grocery receipt on a kitchen table",
"a handheld snapshot of a small dog looking out a car window",
"a natural photo of a rainy suburban street at dusk",
"a casual indoor photo of laundry folded on a couch",
]
SD35_SPEC = APPROVED_GENERATORS["sd3.5-medium"]
def _manifest_path(out_dir: Path) -> Path:
return out_dir.parent / "sd35_medium_manifest.csv"
def main() -> None:
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("--out", type=Path, required=True, help="Output directory")
parser.add_argument(
"--data-root",
type=Path,
default=None,
help=(
"Dataset root for manifest paths. Defaults to the parent of the "
"'raw' path segment in --out."
),
)
parser.add_argument("--count", type=int, default=20_000)
parser.add_argument(
"--prompts",
type=Path,
default=None,
help="Optional file with one prompt per line",
)
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--steps", type=int, default=28)
parser.add_argument("--guidance-scale", type=float, default=4.5)
parser.add_argument("--width", type=int, default=1024)
parser.add_argument("--height", type=int, default=1024)
parser.add_argument(
"--dry-run",
action="store_true",
help="Validate prompt/seed/output planning without loading SD 3.5 or writing files",
)
args = parser.parse_args()
out_dir = args.out.resolve()
out_dir.mkdir(parents=True, exist_ok=True)
data_root = (
args.data_root.resolve()
if args.data_root is not None
else infer_data_root(out_dir)
)
manifest_path = _manifest_path(out_dir)
prompts = load_prompts(args.prompts, fallback_prompts=FALLBACK_PROMPTS)
if args.prompts is not None:
print(f"Loaded {len(prompts)} prompts from {args.prompts}")
else:
print(
f"WARNING: --prompts not given; using {len(prompts)} built-in "
"fallback prompts (smoke-test only, not enough diversity for "
"a real training run)"
)
rng = random.Random(args.seed)
if args.dry_run:
print(
"Dry run: SD 3.5 Medium pipeline will not be loaded and no images "
"will be written."
)
for i in range(args.count):
prompt = choose_prompt(rng, prompts)
seed = next_seed(rng)
key = stable_image_key(prompt, seed)
dst = out_dir / f"{key}.png"
print(f" {i + 1:04d}: seed={seed} path={dst} prompt={prompt!r}")
print(f"Dry run complete. Planned manifest fragment: {manifest_path}")
return
print("Loading SD 3.5 Medium pipeline (large download on first run)...")
import torch
from diffusers import StableDiffusion3Pipeline
pipe = StableDiffusion3Pipeline.from_pretrained(
SD35_SPEC.model_id,
torch_dtype=torch.float16,
)
pipe.to("cuda")
rows: list[dict] = []
for i in range(args.count):
prompt = choose_prompt(rng, prompts)
seed = next_seed(rng)
key = stable_image_key(prompt, seed)
dst = out_dir / f"{key}.png"
if not dst.exists():
generator = torch.Generator("cuda").manual_seed(seed)
image = pipe(
prompt=prompt,
num_inference_steps=args.steps,
guidance_scale=args.guidance_scale,
width=args.width,
height=args.height,
generator=generator,
).images[0]
image.save(dst, format="PNG")
width, height = image_dimensions(dst)
rows.append(
manifest_row(
path=dst.relative_to(data_root).as_posix(),
cls="ai_generated",
spec=SD35_SPEC,
sha256=sha256_file(dst),
prompt=prompt,
seed=seed,
width=width,
height=height,
generation_params={
"steps": args.steps,
"guidance_scale": args.guidance_scale,
"width": args.width,
"height": args.height,
"pipeline": SD35_SPEC.pipeline,
},
)
)
if (i + 1) % 100 == 0:
print(f" generated {i + 1}/{args.count}")
with manifest_path.open("w", newline="") as fh:
writer = csv.DictWriter(fh, fieldnames=STAGE3A_MANIFEST_FIELDS)
writer.writeheader()
writer.writerows(rows)
print(f"Done. {len(rows)} images. Manifest fragment: {manifest_path}")
if __name__ == "__main__":
main()
|