Datasets:
Download tools/background_production.py from laion/Vivarium-Greenscreen-Characters-FLUX-9B: direct link, hf CLI and curl.
- Browser
- Download file 14.7 kB
-
https://huggingface.co/datasets/laion/Vivarium-Greenscreen-Characters-FLUX-9B/resolve/a0d1e3c82a481b094eecf8096cd034ec79b1c62c/tools/background_production.py
- Command line
-
hf download hf://datasets/laion/Vivarium-Greenscreen-Characters-FLUX-9B@a0d1e3c82a481b094eecf8096cd034ec79b1c62c/tools/background_production.py
-
curl -L -o background_production.py https://huggingface.co/datasets/laion/Vivarium-Greenscreen-Characters-FLUX-9B/resolve/a0d1e3c82a481b094eecf8096cd034ec79b1c62c/tools/background_production.py
14.7 kB
| """Resumable eight-GPU generation directly into paired WebDataset TAR members. | |
| Commands: init, worker, upload, status, seal. Authentication is read only from | |
| HF_TOKEN by the upload process; neither credentials nor individual PNG files | |
| are written to disk. SQLite publishes a shard only after its atomic close. | |
| """ | |
| import argparse | |
| import hashlib | |
| import io | |
| import json | |
| import os | |
| from pathlib import Path | |
| import sqlite3 | |
| import tarfile | |
| import time | |
| import traceback | |
| from datetime import datetime, timezone | |
| ROOT = Path(__file__).resolve().parents[1] | |
| STATE = ROOT / 'experiments/background-production' | |
| BUFFER = Path('/tmp/vivarium-background-production') | |
| REPO = 'laion/Anim-E-Ghibli-Backgrounds-FLUX-9B' | |
| BASE_REV = '32773329fbe7e81a90ef971740e8ba4b0364ecf3' | |
| LORA_REV = '5bd654514cc35a1c0d0de878c3a514019896a44e' | |
| LORA_SHA = '253dd23291a64514f7cb107714f2c20118efef930781d620a83417b441198982' | |
| SOURCE_REV = '0c939cef5a586292950724b6500f10ffc5bfa24f' | |
| NEGATIVE = 'people, human figures, characters, crowds, faces, readable text, lettering, logos, watermarks' | |
| def utc(): | |
| return datetime.now(timezone.utc).isoformat() | |
| def dump(path, value): | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| temp = path.with_name(path.name + '.tmp') | |
| temp.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n') | |
| temp.replace(path) | |
| def connect(): | |
| STATE.mkdir(parents=True, exist_ok=True) | |
| con = sqlite3.connect(STATE / 'queue.sqlite', timeout=120) | |
| con.row_factory = sqlite3.Row | |
| con.execute('PRAGMA journal_mode=WAL') | |
| con.execute('PRAGMA busy_timeout=120000') | |
| return con | |
| def init(plan): | |
| con = connect() | |
| con.executescript(''' | |
| CREATE TABLE IF NOT EXISTS jobs ( | |
| id TEXT PRIMARY KEY, position INTEGER, record TEXT NOT NULL, | |
| status TEXT NOT NULL DEFAULT 'queued', worker INTEGER, shard TEXT, | |
| generation_seconds REAL, metadata TEXT, started TEXT, finished TEXT); | |
| CREATE TABLE IF NOT EXISTS shards ( | |
| name TEXT PRIMARY KEY, worker INTEGER, count INTEGER, bytes INTEGER, | |
| sha256 TEXT, status TEXT, revision TEXT, created TEXT, uploaded TEXT); | |
| CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT); | |
| CREATE TABLE IF NOT EXISTS events (time TEXT, worker INTEGER, kind TEXT, detail TEXT); | |
| ''') | |
| records = json.loads(Path(plan).read_text()) | |
| for pos, record in enumerate(records): | |
| prior = con.execute('SELECT record FROM jobs WHERE id=?', (record['id'],)).fetchone() | |
| serialized = json.dumps(record, ensure_ascii=False, sort_keys=True) | |
| if prior and prior['record'] != serialized: | |
| raise ValueError('Refusing to mutate an already queued prompt: ' + record['id']) | |
| con.execute('INSERT OR IGNORE INTO jobs(id,position,record) VALUES(?,?,?)', | |
| (record['id'], pos, serialized)) | |
| con.commit() | |
| print(json.dumps(status(con)), flush=True) | |
| def event(con, worker, kind, detail=''): | |
| con.execute('INSERT INTO events VALUES(?,?,?,?)', (utc(), worker, kind, detail)) | |
| con.commit() | |
| def claim(con, worker): | |
| con.execute('BEGIN IMMEDIATE') | |
| row = con.execute("SELECT * FROM jobs WHERE status='queued' ORDER BY position LIMIT 1").fetchone() | |
| if row: | |
| con.execute("UPDATE jobs SET status='running',worker=?,started=? WHERE id=?", (worker, utc(), row['id'])) | |
| con.commit() | |
| return json.loads(row['record']) if row else None | |
| def sealed(con): | |
| row = con.execute("SELECT value FROM settings WHERE key='sealed'").fetchone() | |
| return bool(row and row['value'] == 'true') | |
| def add_member(tar, name, data): | |
| info = tarfile.TarInfo(name) | |
| info.size = len(data) | |
| info.mtime = 0 | |
| info.mode = 0o644 | |
| tar.addfile(info, io.BytesIO(data)) | |
| def sha(path): | |
| h = hashlib.sha256() | |
| with open(path, 'rb') as f: | |
| for block in iter(lambda: f.read(8 << 20), b''): | |
| h.update(block) | |
| return h.hexdigest() | |
| def worker(gpu, chunk): | |
| import torch | |
| import diffusers | |
| import transformers | |
| from native_flux_inference import create_native_pipeline, generate_native_image | |
| con = connect() | |
| # Restarting a worker safely regenerates only its uncommitted partial shard. | |
| con.execute("UPDATE jobs SET status='queued',worker=NULL WHERE status='running' AND worker=?", (gpu,)) | |
| con.commit() | |
| event(con, gpu, 'loading') | |
| start = time.perf_counter() | |
| pipe = create_native_pipeline('backgrounds', device='cuda:0', compile_mode='default', cfg_mode='batched') | |
| load_seconds = time.perf_counter() - start | |
| event(con, gpu, 'loaded', json.dumps(dict(seconds=load_seconds, gpu=torch.cuda.get_device_name(0)))) | |
| existing = list(BUFFER.glob(f'train-g{gpu}-*.tar')) | |
| sequence = max([int(p.stem.rsplit('-', 1)[1]) for p in existing] + [-1]) + 1 | |
| # Include remotely uploaded/deleted shards when resuming. | |
| rows = con.execute('SELECT name FROM shards WHERE worker=?', (gpu,)).fetchall() | |
| sequence = max(sequence, max([int(r['name'].removesuffix('.tar').rsplit('-', 1)[1]) for r in rows] + [-1]) + 1) | |
| BUFFER.mkdir(parents=True, exist_ok=True) | |
| first = not rows | |
| while True: | |
| samples = [] | |
| tar = None | |
| target = chunk if not first else 2 | |
| for _ in range(target): | |
| record = claim(con, gpu) | |
| if record is None: | |
| if samples or sealed(con): | |
| break | |
| time.sleep(3) | |
| continue | |
| if tar is None: | |
| name = f'train-g{gpu}-{sequence:05d}.tar' | |
| partial = BUFFER / (name + '.partial') | |
| final = BUFFER / name | |
| tar = tarfile.open(partial, 'w', format=tarfile.USTAR_FORMAT) | |
| torch.cuda.synchronize() | |
| begin = time.perf_counter() | |
| try: | |
| image = generate_native_image(pipe, prompt=record['prompt'], seed=record['seed'], | |
| steps=50, guidance=4., negative_prompt=record['negative_prompt'], width=1376, height=768)[0] | |
| torch.cuda.synchronize() | |
| generation_seconds = time.perf_counter() - begin | |
| encoded = io.BytesIO() | |
| image.save(encoded, format='PNG', compress_level=4) | |
| image_bytes = encoded.getvalue() | |
| metadata = dict(record) | |
| metadata.update(dict( | |
| schema_version='1.0', generated_utc=utc(), image_sha256=hashlib.sha256(image_bytes).hexdigest(), | |
| inference=dict(model='black-forest-labs/FLUX.2-klein-base-9B', revision=BASE_REV, | |
| lora='laion/FLUX.2-klein-base-9B-vivarium-loras', lora_revision=LORA_REV, | |
| lora_subfolder='backgrounds', lora_sha256=LORA_SHA, lora_rank=64, lora_alpha=64, | |
| lora_training_step=2000, lora_scale=1.0, steps=50, guidance_scale=4.0, | |
| seed=record['seed'], width=1376, height=768, dtype='bfloat16', quantization=False, | |
| distillation=False, max_sequence_length=256, cfg_mode='batched', lora_fused=True, | |
| qkv_fused=True, compile_mode='default', compile_fullgraph=False, | |
| compile_dynamic=True, negative_embedding_cached=True, | |
| scheduler=type(pipe.scheduler).__name__, scheduler_config=dict(pipe.scheduler.config), | |
| reference_images=[]), | |
| runtime=dict(gpu_index=gpu, gpu=torch.cuda.get_device_name(0), batch_size=1, | |
| generation_seconds=generation_seconds, includes_compile_warmup=first and not samples, | |
| model_load_seconds=load_seconds, torch=torch.__version__, cuda=torch.version.cuda, | |
| diffusers=diffusers.__version__, transformers=transformers.__version__, | |
| diffusers_commit='899c9f3fd0e64f3206781c00c71c28249eff9ca5'), | |
| storage=dict(shard=name, image_member=record['id']+'.png', json_member=record['id']+'.json', | |
| prompt_member=record['id']+'.txt', encoding='PNG RGB', png_compress_level=4))) | |
| add_member(tar, record['id']+'.png', image_bytes) | |
| add_member(tar, record['id']+'.json', json.dumps(metadata, ensure_ascii=False, indent=2).encode()) | |
| add_member(tar, record['id']+'.txt', record['prompt'].encode()) | |
| samples.append((record['id'], generation_seconds, json.dumps(metadata, ensure_ascii=False))) | |
| event(con, gpu, 'image', json.dumps(dict(id=record['id'], seconds=generation_seconds))) | |
| print(json.dumps(dict(gpu=gpu, id=record['id'], seconds=round(generation_seconds, 2))), flush=True) | |
| except Exception: | |
| event(con, gpu, 'error', traceback.format_exc()) | |
| raise | |
| if tar: | |
| tar.close() | |
| partial.replace(final) | |
| digest = sha(final) | |
| con.execute('BEGIN IMMEDIATE') | |
| con.execute('INSERT INTO shards VALUES(?,?,?,?,?,?,?,?,?)', | |
| (name, gpu, len(samples), final.stat().st_size, digest, 'ready', None, utc(), None)) | |
| for ident, seconds, metadata in samples: | |
| con.execute("UPDATE jobs SET status='done',shard=?,generation_seconds=?,metadata=?,finished=? WHERE id=?", | |
| (name, seconds, metadata, utc(), ident)) | |
| con.commit() | |
| event(con, gpu, 'shard', name) | |
| sequence += 1 | |
| first = False | |
| if not samples and sealed(con): | |
| break | |
| event(con, gpu, 'complete') | |
| print('Worker complete', gpu, flush=True) | |
| def status(con=None): | |
| con = con or connect() | |
| jobs = {r[0]:r[1] for r in con.execute('SELECT status,COUNT(*) FROM jobs GROUP BY status')} | |
| shards = {r[0]:r[1] for r in con.execute('SELECT status,COUNT(*) FROM shards GROUP BY status')} | |
| open_images=con.execute("""SELECT COUNT(DISTINCT j.id) FROM jobs j JOIN events e | |
| ON e.kind='image' AND json_extract(e.detail,'$.id')=j.id | |
| WHERE j.status='running' AND e.time>=j.started""").fetchone()[0] | |
| generated=jobs.get('done',0)+open_images | |
| seconds=con.execute("""SELECT AVG(seconds) FROM ( | |
| SELECT json_extract(detail,'$.seconds') AS seconds, | |
| ROW_NUMBER() OVER (PARTITION BY worker ORDER BY rowid) AS sequence | |
| FROM events WHERE kind='image') WHERE sequence>1""").fetchone()[0] | |
| return dict(utc=utc(), jobs=jobs, shards=shards, sealed=sealed(con), steady_mean_seconds=seconds, | |
| images_generated=generated, images_in_open_shards=open_images, | |
| images_currently_generating=jobs.get('running',0)-open_images, | |
| inference_attempts_completed=con.execute("SELECT COUNT(*) FROM events WHERE kind='image'").fetchone()[0], | |
| buffer_free_gb=os.statvfs(BUFFER if BUFFER.exists() else '/tmp').f_bavail * os.statvfs('/tmp').f_frsize / 1e9) | |
| def upload(delete_after=False): | |
| from huggingface_hub import HfApi | |
| token = os.environ.get('HF_TOKEN') | |
| if not token: | |
| raise RuntimeError('HF_TOKEN must be supplied only through the process environment') | |
| api = HfApi(token=token) | |
| con = connect() | |
| while True: | |
| # First 16 production images are reviewed as contact sheets before | |
| # allowing any image publication. Other workers continue generating. | |
| if not (STATE / 'quality-gate-passed.json').is_file(): | |
| time.sleep(5) | |
| continue | |
| rows = con.execute("SELECT * FROM shards WHERE status='ready' ORDER BY created").fetchall() | |
| for row in rows: | |
| local = BUFFER / row['name'] | |
| try: | |
| if sha(local) != row['sha256']: | |
| raise ValueError('Local shard checksum mismatch: ' + row['name']) | |
| result = api.upload_file(path_or_fileobj=local, path_in_repo='data/'+row['name'], | |
| repo_id=REPO, repo_type='dataset', commit_message=f"Add {row['count']} backgrounds: {row['name']}") | |
| remote = api.dataset_info(REPO, revision=result.oid, files_metadata=True) | |
| file = next(f for f in remote.siblings if f.rfilename == 'data/'+row['name']) | |
| remote_digest = file.lfs.sha256 if file.lfs else None | |
| if file.size != row['bytes'] or remote_digest != row['sha256']: | |
| raise ValueError('Remote size/SHA256 mismatch: ' + row['name']) | |
| con.execute("UPDATE shards SET status='uploaded',revision=?,uploaded=? WHERE name=?", (result.oid, utc(), row['name'])) | |
| con.commit() | |
| event(con, -1, 'uploaded', json.dumps(dict(name=row['name'], revision=result.oid))) | |
| print(json.dumps(dict(uploaded=row['name'], images=row['count'], revision=result.oid)), flush=True) | |
| # Only verified remote content is eligible for local removal. | |
| free = os.statvfs(BUFFER).f_bavail * os.statvfs(BUFFER).f_frsize | |
| if delete_after or free < 30_000_000_000: | |
| local.unlink() | |
| event(con, -1, 'buffer_deleted', row['name']) | |
| except Exception as exc: | |
| event(con, -1, 'upload_error', str(exc)) | |
| print('Upload will retry:', type(exc).__name__, str(exc), flush=True) | |
| time.sleep(10) | |
| state = status(con) | |
| dump(STATE / 'progress.json', state) | |
| unfinished = con.execute("SELECT COUNT(*) FROM jobs WHERE status!='done'").fetchone()[0] | |
| unuploaded = con.execute("SELECT COUNT(*) FROM shards WHERE status!='uploaded'").fetchone()[0] | |
| if sealed(con) and not unfinished and not unuploaded: | |
| print('All generated shards uploaded and checksummed', flush=True) | |
| return | |
| time.sleep(5) | |
| if __name__ == '__main__': | |
| parser = argparse.ArgumentParser() | |
| sub = parser.add_subparsers(dest='command', required=True) | |
| ini = sub.add_parser('init'); ini.add_argument('plan', type=Path) | |
| wor = sub.add_parser('worker'); wor.add_argument('--gpu', type=int, required=True); wor.add_argument('--chunk', type=int, default=24) | |
| up = sub.add_parser('upload'); up.add_argument('--delete-after', action='store_true') | |
| sub.add_parser('status'); sub.add_parser('seal') | |
| args = parser.parse_args() | |
| if args.command == 'init': init(args.plan) | |
| elif args.command == 'worker': worker(args.gpu, args.chunk) | |
| elif args.command == 'upload': upload(args.delete_after) | |
| elif args.command == 'status': print(json.dumps(status(), indent=2)) | |
| elif args.command == 'seal': | |
| con=connect(); con.execute("INSERT OR REPLACE INTO settings VALUES('sealed','true')"); con.commit() | |