ChristophSchuhmann's picture
Update characters documentation, taxonomy, measured progress and validation
302855b verified
Raw History Blame
12.3 kB
"""500 identity groups with neutral references and ten paired TAR samples each."""
import argparse
import hashlib
import io
import json
import os
from pathlib import Path
import sqlite3
import tarfile
import time
from datetime import datetime,timezone,timedelta
from background_production import add_member,sha,dump
ROOT=Path(__file__).resolve().parents[1]
STATE=ROOT/'experiments/character-production'
BUFFER=Path('/tmp/vivarium-character-production')
REPO='laion/Vivarium-Greenscreen-Characters-FLUX-9B'
def utc():return datetime.now(timezone.utc).isoformat()
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():
con=connect()
con.executescript('''
CREATE TABLE IF NOT EXISTS people (id TEXT PRIMARY KEY,position INTEGER,record TEXT,status TEXT DEFAULT 'queued',worker INTEGER,started TEXT,finished TEXT);
CREATE TABLE IF NOT EXISTS images (id TEXT PRIMARY KEY,person_id TEXT,emotion TEXT,shard TEXT,metadata 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 events (time TEXT,worker INTEGER,kind TEXT,detail TEXT);
''')
plan=json.loads((STATE/'person-plan.json').read_text());groups={}
for person in plan:groups.setdefault((person['age_group'],person['gender']),[]).append(person)
order=[]
for cycle in range(12):
for first in [True,False]:
for cell,(key,people) in enumerate(groups.items()):
index=2*cycle+(cell%2 if first else 1-cell%2)
if index<len(people):order.append(people[index])
assert len(order)==500 and len({p['personality_id'] for p in order})==500
for pos,person in enumerate(order):
record=json.dumps(person,ensure_ascii=False,sort_keys=True)
prior=con.execute('SELECT record FROM people WHERE id=?',(person['personality_id'],)).fetchone()
if prior:assert prior['record']==record,'Refusing to mutate an initialized identity'
con.execute('INSERT OR IGNORE INTO people(id,position,record) VALUES(?,?,?)',(person['personality_id'],pos,record))
con.commit();print(json.dumps(status(con),indent=2))
def event(con,worker,kind,detail=''):
con.execute('INSERT INTO events VALUES(?,?,?,?)',(utc(),worker,kind,detail));con.commit()
def claim(con,gpu):
con.execute('BEGIN IMMEDIATE')
row=con.execute("SELECT * FROM people WHERE status='queued' ORDER BY position LIMIT 1").fetchone()
if row:con.execute("UPDATE people SET status='running',worker=?,started=? WHERE id=?",(gpu,utc(),row['id']))
con.commit();return json.loads(row['record']) if row else None
def status(con=None):
con=con or connect();people={r[0]:r[1] for r in con.execute('SELECT status,COUNT(*) FROM people GROUP BY status')}
shards={r[0]:r[1] for r in con.execute('SELECT status,COUNT(*) FROM shards GROUP BY status')}
committed=con.execute('SELECT COUNT(*) FROM images').fetchone()[0]
open_count=con.execute("""SELECT COUNT(DISTINCT json_extract(e.detail,'$.id'))
FROM events e JOIN people p ON p.id=substr(json_extract(e.detail,'$.id'),1,11)
WHERE e.kind='image' AND p.status='running' AND e.time>=p.started""").fetchone()[0]
return dict(utc=utc(),people=people,shards=shards,images_in_closed_shards=committed,
images_generated=committed+max(open_count,0),target_people=500,target_images=5000,
images_uploaded=con.execute("SELECT COALESCE(SUM(count),0) FROM shards WHERE status='uploaded'").fetchone()[0],
buffer_free_gb=os.statvfs('/tmp').f_bavail*os.statvfs('/tmp').f_frsize/1e9)
def ingest_pilot():
assert (STATE/'pilot-quality-passed.json').is_file(),'Review reference identity,emotion and outfits before accepting pilot'
con=connect();plan={p['personality_id']:p for p in json.loads((STATE/'person-plan.json').read_text())}
for path in sorted(BUFFER.glob('pilot-person-*.tar')):
if con.execute('SELECT name FROM shards WHERE name=?',(path.name,)).fetchone():continue
records=[]
bg=sqlite3.connect(ROOT/'experiments/background-production/queue.sqlite')
end=bg.execute("SELECT MAX(time) FROM events WHERE worker=7 AND kind='complete'").fetchone()[0];bg.close()
assert end,'Background GPU7 must have completed before pilot ingestion'
corrected=path.with_name(path.name+'.runtimefix')
with tarfile.open(path,'r:') as src,tarfile.open(corrected,'w',format=tarfile.USTAR_FORMAT) as dst:
for member in src:
data=src.extractfile(member).read()
if member.name.endswith('.json'):
m=json.loads(data)
start=datetime.fromisoformat(m['generated_utc'])-timedelta(seconds=m['runtime']['generation_seconds'])
m['runtime']['gpu_shared_with_backgrounds']=start<datetime.fromisoformat(end)
m['runtime']['sharing_note']='GPU7 background worker completed at '+end+'; shared flag reflects overlap with this generation call'
data=json.dumps(m,indent=2,ensure_ascii=False).encode()
add_member(dst,member.name,data)
corrected.replace(path)
with tarfile.open(path,'r:') as tar:
for member in tar:
if member.name.endswith('.json'):records.append(json.loads(tar.extractfile(member).read()))
ident=records[0]['personality_id'];person=plan[ident]
assert len(records)==10 and {r['emotion'] for r in records}=={e['emotion'] for e in person['expressions']}
for record in records:
expected=next(e for e in person['expressions'] if e['id']==record['id'])
for k,v in expected.items():assert record[k]==v,(record['id'],k)
con.execute('BEGIN IMMEDIATE')
con.execute('INSERT INTO shards VALUES(?,?,?,?,?,?,?,?,?)',(path.name,7,10,path.stat().st_size,sha(path),'ready',None,utc(),None))
for m in records:
con.execute('INSERT INTO images VALUES(?,?,?,?,?)',(m['id'],ident,m['emotion'],path.name,json.dumps(m,ensure_ascii=False)))
con.execute('INSERT INTO events VALUES(?,?,?,?)',(m['generated_utc'],7,'image',json.dumps(dict(id=m['id'],seconds=m['runtime']['generation_seconds'],pilot=True))))
con.execute("UPDATE people SET status='done',worker=7,finished=? WHERE id=?",(utc(),ident));con.commit()
print(json.dumps(status(con),indent=2))
def worker(gpu):
import torch
from PIL import Image
from native_flux_inference import create_native_pipeline,generate_native_image,encode_text
from character_pilot import metadata
con=connect();con.execute("UPDATE people SET status='queued',worker=NULL WHERE status='running' AND worker=?",(gpu,));con.commit()
event(con,gpu,'loading');pipe=create_native_pipeline('characters',device='cuda:0',compile_mode='default',cfg_mode='batched')
event(con,gpu,'loaded')
rows=con.execute('SELECT name FROM shards WHERE worker=? AND name LIKE ?',(gpu,f'train-g{gpu}-%')).fetchall()
sequence=max([int(r['name'].removesuffix('.tar').rsplit('-',1)[1]) for r in rows]+[-1])+1
BUFFER.mkdir(parents=True,exist_ok=True);first=True
while True:
records=[];person_ids=[];tar=None
for _ in range(1 if first else 2):
person=claim(con,gpu)
if person is None:break
if tar is None:
name=f'train-g{gpu}-{sequence:05d}.tar';partial=BUFFER/(name+'.partial');tar=tarfile.open(partial,'w',format=tarfile.USTAR_FORMAT)
cache={};encoding={}
for e in person['expressions']:
start=time.perf_counter();cache[e['id']]=encode_text(pipe,e['prompt']);torch.cuda.synchronize();encoding[e['id']]=time.perf_counter()-start
if e['negative_prompt'] not in pipe._native_text_cache:pipe._native_text_cache[e['negative_prompt']]=encode_text(pipe,e['negative_prompt'])
reference=None;reference_sha=''
for e in person['expressions']:
torch.cuda.synchronize();start=time.perf_counter()
im=generate_native_image(pipe,prompt_embeds=cache[e['id']],seed=e['seed'],steps=50,guidance=4.,
negative_prompt=e['negative_prompt'],image=reference if e['emotion']!='neutral' else None,width=832,height=1248)[0]
torch.cuda.synchronize();seconds=time.perf_counter()-start
b=io.BytesIO();im.save(b,format='PNG',compress_level=4);png=b.getvalue()
m=metadata(person,e,png,reference_sha,seconds,encoding[e['id']],name,'dedicated-GPU-preencoded-production')
m['runtime']['includes_compile_warmup']=first and e['emotion'] in ['neutral','joyful']
add_member(tar,e['id']+'.png',png);add_member(tar,e['id']+'.json',json.dumps(m,ensure_ascii=False,indent=2).encode());add_member(tar,e['id']+'.txt',e['prompt'].encode())
records.append(m);event(con,gpu,'image',json.dumps(dict(id=e['id'],seconds=seconds,pilot=False)))
print(json.dumps(dict(id=e['id'],gpu=gpu,seconds=round(seconds,2))),flush=True)
if e['emotion']=='neutral':reference=im.resize((416,624),Image.Resampling.BICUBIC);reference_sha=hashlib.sha256(png).hexdigest()
person_ids.append(person['personality_id']);first=False
if tar:
tar.close();final=BUFFER/name;partial.replace(final)
con.execute('BEGIN IMMEDIATE')
con.execute('INSERT INTO shards VALUES(?,?,?,?,?,?,?,?,?)',(name,gpu,len(records),final.stat().st_size,sha(final),'ready',None,utc(),None))
for m in records:con.execute('INSERT INTO images VALUES(?,?,?,?,?)',(m['id'],m['personality_id'],m['emotion'],name,json.dumps(m,ensure_ascii=False)))
for ident in person_ids:con.execute("UPDATE people SET status='done',finished=? WHERE id=?",(utc(),ident))
con.commit();sequence+=1
if not person_ids:break
event(con,gpu,'complete');print('Character worker complete',gpu,flush=True)
def upload():
from huggingface_hub import HfApi
api=HfApi(token=os.environ['HF_TOKEN']);con=connect()
while True:
if not (STATE/'production-quality-passed.json').is_file() and not (STATE/'pilot-quality-passed.json').is_file():
time.sleep(5);continue
for r in con.execute("SELECT * FROM shards WHERE status='ready' ORDER BY created").fetchall():
try:
path=BUFFER/r['name'];assert sha(path)==r['sha256']
commit=api.upload_file(path_or_fileobj=path,path_in_repo='data/'+r['name'],repo_id=REPO,repo_type='dataset',commit_message=f"Add {r['count']} greenscreen emotion images: {r['name']}")
info=api.dataset_info(REPO,revision=commit.oid,files_metadata=True);remote=next(f for f in info.siblings if f.rfilename=='data/'+r['name'])
assert remote.size==r['bytes'] and remote.lfs.sha256==r['sha256']
con.execute("UPDATE shards SET status='uploaded',revision=?,uploaded=? WHERE name=?",(commit.oid,utc(),r['name']));con.commit()
print(json.dumps(dict(uploaded=r['name'],images=r['count'],revision=commit.oid)),flush=True)
if os.statvfs('/tmp').f_bavail*os.statvfs('/tmp').f_frsize<30_000_000_000:
path.unlink();event(con,-1,'buffer_deleted',r['name'])
except Exception as exc:
print('Upload retry:',type(exc).__name__,str(exc),flush=True);time.sleep(10)
progress=status(con);dump(STATE/'progress.json',progress)
if progress['people'].get('done')==500 and progress['images_uploaded']==5000:return
time.sleep(5)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('command',choices=['init','worker','ingest-pilot','status','upload']);p.add_argument('--gpu',type=int);a=p.parse_args()
if a.command=='init':init()
elif a.command=='worker':worker(a.gpu)
elif a.command=='ingest-pilot':ingest_pilot()
elif a.command=='upload':upload()
elif a.command=='status':print(json.dumps(status(),indent=2))