Datasets:
Download tools/character_pilot.py from laion/Vivarium-Greenscreen-Characters-FLUX-9B: direct link, hf CLI and curl.
- Browser
- Download file 6.66 kB
-
https://huggingface.co/datasets/laion/Vivarium-Greenscreen-Characters-FLUX-9B/resolve/a0d1e3c82a481b094eecf8096cd034ec79b1c62c/tools/character_pilot.py
- Command line
-
hf download hf://datasets/laion/Vivarium-Greenscreen-Characters-FLUX-9B@a0d1e3c82a481b094eecf8096cd034ec79b1c62c/tools/character_pilot.py
-
curl -L -o character_pilot.py https://huggingface.co/datasets/laion/Vivarium-Greenscreen-Characters-FLUX-9B/resolve/a0d1e3c82a481b094eecf8096cd034ec79b1c62c/tools/character_pilot.py
6.66 kB
| """Reference-expression pilot alongside background generation on one shared GPU.""" | |
| import hashlib | |
| import io | |
| import json | |
| import os | |
| from pathlib import Path | |
| import tarfile | |
| import time | |
| from datetime import datetime,timezone | |
| import torch | |
| from PIL import Image | |
| from native_flux_inference import create_native_pipeline, generate_native_image, encode_text | |
| from background_production import add_member,dump,BASE_REV,LORA_REV | |
| ROOT=Path(__file__).resolve().parents[1] | |
| STATE=ROOT/'experiments/character-production' | |
| BUFFER=Path('/tmp/vivarium-character-production') | |
| LORA_SHA='977642f4d7427fa3203b5b3b3c3a4ef9cb72186c59bd71b63e870ff53bfa6451' | |
| def now():return datetime.now(timezone.utc).isoformat() | |
| def metadata(person,expression,image_bytes,reference_sha,seconds,encode_seconds,shard,profile): | |
| record={k:v for k,v in person.items() if k!='expressions'} | |
| record.update(expression) | |
| record.update(dict(schema_version='1.0',generated_utc=now(),image_sha256=hashlib.sha256(image_bytes).hexdigest(), | |
| reference_image_sha256=reference_sha,reference_resize=dict(width=416 if reference_sha else 0,height=624 if reference_sha else 0,resample='PIL BICUBIC' if reference_sha else ''), | |
| 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='characters', | |
| lora_sha256=LORA_SHA,lora_rank=64,lora_alpha=64,lora_training_step=1500,lora_scale=1.0, | |
| steps=50,guidance_scale=4.0,seed=expression['seed'],width=832,height=1248,dtype='bfloat16', | |
| quantization=False,distillation=False,max_sequence_length=256,cfg_mode='batched',lora_fused=True, | |
| qkv_fused=True,compile_mode='default',negative_embedding_cached=True,positive_embedding_cached=True), | |
| runtime=dict(profile=profile,gpu=torch.cuda.get_device_name(0),physical_gpu=int(os.environ.get('CUDA_VISIBLE_DEVICES','0')), | |
| batch_size=1,generation_seconds=seconds,positive_text_encoding_seconds=encode_seconds, | |
| torch=torch.__version__,cuda=torch.version.cuda,includes_compile_warmup=False, | |
| gpu_shared_with_backgrounds=profile.startswith('shared'),model_cpu_offload=profile.startswith('shared')), | |
| storage=dict(shard=shard,image_member=expression['id']+'.png',json_member=expression['id']+'.json',prompt_member=expression['id']+'.txt',encoding='PNG RGB'))) | |
| return record | |
| def main(): | |
| BUFFER.mkdir(parents=True,exist_ok=True) | |
| plan=json.loads((STATE/'person-plan.json').read_text()) | |
| ids=['person-0002','person-0120','person-0253'] | |
| people=[next(p for p in plan if p['personality_id']==i) for i in ids] | |
| dump(STATE/'pilot-state.json',dict(status='loading CPU-offloaded pipeline',ids=ids,utc=now())) | |
| pipe=create_native_pipeline('characters',device='cpu',compile_mode='default',cfg_mode='batched') | |
| pipe.enable_model_cpu_offload(gpu_id=0) | |
| cache={};encode_times={} | |
| for p in people: | |
| for e in p['expressions']: | |
| start=time.perf_counter();cache[e['id']]=encode_text(pipe,e['prompt']).cpu();torch.cuda.synchronize() | |
| encode_times[e['id']]=time.perf_counter()-start | |
| neg=p['expressions'][0]['negative_prompt'] | |
| if neg not in pipe._native_text_cache:pipe._native_text_cache[neg]=encode_text(pipe,neg) | |
| dump(STATE/'pilot-state.json',dict(status='generating',ids=ids,preencoded_prompts=len(cache),utc=now())) | |
| all_records=[];references={};reference_shas={};archives={} | |
| for p in people: | |
| name='pilot-'+p['personality_id']+'.tar' | |
| archives[p['personality_id']]=tarfile.open(BUFFER/(name+'.partial'),'w',format=tarfile.USTAR_FORMAT) | |
| # Inspect every age group's neutral image early, then prioritize visible | |
| # expressions. Only accepted neutral pixels are reused from the first pilot. | |
| order=['neutral','angry','joyful','sad','afraid','disgust','pain','annoyed','grateful','playful'] | |
| first_generated=True | |
| for emotion in order: | |
| for p in people: | |
| ident=p['personality_id'];e=next(x for x in p['expressions'] if x['emotion']==emotion) | |
| name='pilot-'+ident+'.tar';tar=archives[ident];bootstrap=None | |
| if ident=='person-0002' and emotion=='neutral': | |
| prior=list((BUFFER/'pilot-first-pass').glob('pilot-person-0002.tar*')) | |
| if prior: | |
| with tarfile.open(prior[0],'r:') as old: | |
| png_member=old.next();png=old.extractfile(png_member).read() | |
| json_member=old.next();bootstrap=json.loads(old.extractfile(json_member).read()) | |
| assert bootstrap['id']==e['id'] and bootstrap['prompt']==e['prompt'] | |
| with Image.open(io.BytesIO(png)) as im:image=im.convert('RGB') | |
| m=bootstrap | |
| if bootstrap is None: | |
| torch.cuda.synchronize();start=time.perf_counter() | |
| image=generate_native_image(pipe,prompt_embeds=cache[e['id']].to(pipe._execution_device),seed=e['seed'], | |
| steps=50,guidance=4.,negative_prompt=e['negative_prompt'],image=references.get(ident) if emotion!='neutral' else None, | |
| width=832,height=1248)[0] | |
| torch.cuda.synchronize();seconds=time.perf_counter()-start | |
| encoded=io.BytesIO();image.save(encoded,format='PNG',compress_level=4);png=encoded.getvalue() | |
| m=metadata(p,e,png,reference_shas.get(ident,''),seconds,encode_times[e['id']],name,'shared-GPU7-CPU-offload-preencoded-pilot') | |
| m['runtime']['includes_compile_warmup']=first_generated | |
| first_generated=False | |
| add_member(tar,e['id']+'.png',png);add_member(tar,e['id']+'.json',json.dumps(m,indent=2,ensure_ascii=False).encode());add_member(tar,e['id']+'.txt',e['prompt'].encode()) | |
| tar.fileobj.flush() | |
| all_records.append(m) | |
| if emotion=='neutral': | |
| references[ident]=image.resize((416,624),Image.Resampling.BICUBIC);reference_shas[ident]=hashlib.sha256(png).hexdigest() | |
| print(json.dumps(dict(id=e['id'],seconds=round(m['runtime']['generation_seconds'],2))),flush=True) | |
| dump(STATE/'pilot-records.json',all_records) | |
| dump(STATE/'pilot-state.json',dict(status='generating',images_completed=len(all_records),latest=e['id'],utc=now())) | |
| for ident,tar in archives.items(): | |
| tar.close();name='pilot-'+ident+'.tar';(BUFFER/(name+'.partial')).replace(BUFFER/name) | |
| dump(STATE/'pilot-state.json',dict(status='complete',images_completed=len(all_records),ids=ids,utc=now())) | |
| if __name__=='__main__':main() | |