Datasets:
Download tools/native_flux_inference.py from laion/Vivarium-Greenscreen-Characters-FLUX-9B: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/datasets/laion/Vivarium-Greenscreen-Characters-FLUX-9B/resolve/a0d1e3c82a481b094eecf8096cd034ec79b1c62c/tools/native_flux_inference.py
- Command line
-
hf download hf://datasets/laion/Vivarium-Greenscreen-Characters-FLUX-9B@a0d1e3c82a481b094eecf8096cd034ec79b1c62c/tools/native_flux_inference.py
-
curl -L -o native_flux_inference.py https://huggingface.co/datasets/laion/Vivarium-Greenscreen-Characters-FLUX-9B/resolve/a0d1e3c82a481b094eecf8096cd034ec79b1c62c/tools/native_flux_inference.py
10 kB
| """Undistilled FLUX9B with real CFG, negative prompts and reference images. | |
| CFG batching/parallelism change execution layout, not the guidance equation. | |
| The denoising call is derived from the pinned installed official pipeline; | |
| only its two transformer calls are replaced. No approximation cache is used. | |
| """ | |
| import copy | |
| import inspect | |
| import json | |
| import textwrap | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| import torch | |
| from diffusers import Flux2KleinPipeline | |
| import diffusers.pipelines.flux2.pipeline_flux2_klein as upstream | |
| from vivarium_prompt_templates import build_prompt | |
| ROOT = Path(__file__).resolve().parents[1] | |
| def _forward(model, kwargs, device): | |
| with torch.inference_mode(), torch.autocast(device.type, dtype=torch.bfloat16): | |
| return model(**kwargs)[0] | |
| def _cfg_prediction(self, hidden, timestep, positive, negative, txt, neg_txt, img, image_tokens): | |
| if getattr(self,'_native_mark_graph_steps',False): | |
| torch.compiler.cudagraph_mark_step_begin() | |
| common = dict(hidden_states=hidden, timestep=timestep/1000, guidance=None, img_ids=img, | |
| joint_attention_kwargs=self.attention_kwargs, return_dict=False) | |
| pos = dict(common, encoder_hidden_states=positive, txt_ids=txt) | |
| if not self.do_classifier_free_guidance: | |
| return self.transformer(**pos)[0][:,:image_tokens] | |
| neg = dict(common, encoder_hidden_states=negative, txt_ids=neg_txt) | |
| mode = self._native_cfg_mode | |
| if mode == 'batched': | |
| merged = dict(common, hidden_states=torch.cat([hidden,hidden],dim=0), | |
| timestep=torch.cat([timestep,timestep],dim=0)/1000, | |
| encoder_hidden_states=torch.cat([positive,negative],dim=0), | |
| txt_ids=torch.cat([txt,neg_txt],dim=0), img_ids=torch.cat([img,img],dim=0)) | |
| pred = self.transformer(**merged)[0][:,:image_tokens] | |
| positive_noise, negative_noise = pred.chunk(2,dim=0) | |
| elif mode == 'parallel': | |
| device=self._native_second_device | |
| neg={k:(v.to(device) if isinstance(v,torch.Tensor) else v) for k,v in neg.items()} | |
| future=self._native_executor.submit(_forward,self._native_negative_transformer,neg,device) | |
| positive_noise=self.transformer(**pos)[0][:,:image_tokens] | |
| negative_noise=future.result()[:,:image_tokens].to(hidden.device) | |
| else: | |
| with self.transformer.cache_context('cond'): positive_noise=self.transformer(**pos)[0][:,:image_tokens] | |
| with self.transformer.cache_context('uncond'): negative_noise=self.transformer(**neg)[0][:,:image_tokens] | |
| return negative_noise+self.guidance_scale*(positive_noise-negative_noise) | |
| def _native_call(): | |
| source=textwrap.dedent(inspect.getsource(inspect.unwrap(Flux2KleinPipeline.__call__))) | |
| source=source[source.index('def __call__('):] | |
| start=source.index(' with self.transformer.cache_context("cond"):') | |
| end=source.index(' # compute the previous noisy sample',start) | |
| old=source[start:end] | |
| assert old.count('self.transformer(')==2 and 'neg_noise_pred + guidance_scale' in old | |
| new=''' noise_pred = self._native_cfg_prediction( | |
| latent_model_input, timestep, prompt_embeds, | |
| negative_prompt_embeds if self.do_classifier_free_guidance else None, | |
| text_ids, negative_text_ids if self.do_classifier_free_guidance else None, | |
| latent_image_ids, latents.size(1)) | |
| ''' | |
| namespace=dict(vars(upstream)) | |
| exec(compile(source[:start]+new+source[end:],'<pinned-flux-native-cfg>','exec'),namespace) | |
| return torch.no_grad()(namespace['__call__']) | |
| class NativeFluxPipeline(Flux2KleinPipeline): | |
| __call__=_native_call() | |
| _native_cfg_prediction=_cfg_prediction | |
| def create_native_pipeline(kind='characters', device='cuda:0', fuse=True, qkv=True, | |
| compile_mode='default', cfg_mode='batched', second_device='cuda:1',base_path=None): | |
| assert kind in ('characters','backgrounds') and cfg_mode in ('sequential','batched','parallel') | |
| torch.set_num_threads(8) | |
| torch.backends.cuda.matmul.allow_tf32=True | |
| registry=ROOT/'model-downloads.json' | |
| model=json.loads(registry.read_text())['FLUX.2-klein-base-9B'] if registry.is_file() else dict(repo='black-forest-labs/FLUX.2-klein-base-9B',revision='32773329fbe7e81a90ef971740e8ba4b0364ecf3',path='/nonexistent-vivarium-base-cache') | |
| path=Path(base_path) if base_path else Path(model['path']) | |
| if base_path is None and not path.is_absolute(): path=ROOT/path | |
| kwargs=dict(torch_dtype=torch.bfloat16) | |
| if path.is_dir(): kwargs['local_files_only']=True | |
| else: kwargs['revision']=model['revision'] | |
| pipe=NativeFluxPipeline.from_pretrained(str(path) if path.is_dir() else model['repo'],**kwargs).to(device) | |
| assert not pipe.config.is_distilled, 'Only undistilled base9B is permitted.' | |
| pipe.set_progress_bar_config(disable=True) | |
| adapter=ROOT/'outputs/9B'/kind/'selected/pytorch_lora_weights.safetensors' | |
| if not adapter.is_file(): adapter=ROOT/'loras'/f'flux-{kind}.safetensors' | |
| if not adapter.is_file(): adapter=ROOT/kind/'pytorch_lora_weights.safetensors' | |
| if adapter.is_file(): | |
| pipe.load_lora_weights(str(adapter.parent),weight_name=adapter.name,adapter_name='vivarium') | |
| else: | |
| pipe.load_lora_weights('laion/FLUX.2-klein-base-9B-vivarium-loras',revision='5bd654514cc35a1c0d0de878c3a514019896a44e',subfolder=kind,weight_name='pytorch_lora_weights.safetensors',adapter_name='vivarium') | |
| pipe.set_adapters('vivarium',adapter_weights=1.) | |
| if fuse: | |
| pipe.fuse_lora(adapter_names=['vivarium'],safe_fusing=True) | |
| pipe.unload_lora_weights() | |
| if qkv: | |
| assert fuse, 'Fuse adapter projections before fusing QKV.' | |
| pipe.transformer.fuse_qkv_projections() | |
| pipe.transformer.eval() | |
| pipe._native_cfg_mode=cfg_mode | |
| pipe._native_mark_graph_steps=compile_mode=='reduce-overhead' | |
| if pipe._native_mark_graph_steps: assert cfg_mode=='batched', 'CUDAGraph profile requires batched CFG.' | |
| pipe._native_kind=kind | |
| pipe._native_text_cache={} | |
| if cfg_mode=='parallel': | |
| second=torch.device(second_device) | |
| assert torch.device(device)!=second | |
| pipe._native_second_device=second | |
| pipe._native_negative_transformer=copy.deepcopy(pipe.transformer).to(second).eval() | |
| pipe._native_executor=ThreadPoolExecutor(max_workers=1) | |
| if compile_mode: | |
| # Repeated blocks carry distinct attention processors. Keep their guards | |
| # cached across both resolutions and successive category pipelines. | |
| torch._dynamo.config.cache_size_limit=1024 | |
| for transformer in ([pipe.transformer,pipe._native_negative_transformer] if cfg_mode=='parallel' else [pipe.transformer]): | |
| transformer.compile_repeated_blocks(fullgraph=False,dynamic=compile_mode!='reduce-overhead',mode=compile_mode) | |
| return pipe | |
| def encode_text(pipe,text): | |
| with torch.inference_mode(),torch.autocast(pipe._execution_device.type,dtype=torch.bfloat16): | |
| return pipe.encode_prompt(text,device=pipe._execution_device,max_sequence_length=256)[0] | |
| def generate_native_image(pipe,prompt=None,seed=28008,steps=50,guidance=4.,negative_prompt='',image=None, | |
| width=None,height=None,cache_negative=True,prompt_embeds=None,description=None): | |
| assert steps in (40,50), 'Production trials retain40 or50 denoising steps.' | |
| if prompt is not None and description is not None: | |
| raise ValueError('Use a full prompt or a templated description, not both.') | |
| if prompt is None and prompt_embeds is None: prompt=build_prompt(pipe._native_kind,description) | |
| kwargs=dict(width=width or (832 if pipe._native_kind=='characters' else 1376), | |
| height=height or (1248 if pipe._native_kind=='characters' else 768), | |
| num_inference_steps=steps,guidance_scale=guidance,max_sequence_length=256, | |
| generator=torch.Generator(pipe._execution_device).manual_seed(seed)) | |
| if prompt_embeds is None: kwargs['prompt']=prompt | |
| else: kwargs['prompt_embeds']=prompt_embeds | |
| if image is not None: kwargs['image']=image | |
| with torch.inference_mode(),torch.autocast(pipe._execution_device.type,dtype=torch.bfloat16): | |
| if guidance>1 and (cache_negative or negative_prompt): | |
| if negative_prompt not in pipe._native_text_cache: | |
| pipe._native_text_cache[negative_prompt]=encode_text(pipe,negative_prompt) | |
| kwargs['negative_prompt_embeds']=pipe._native_text_cache[negative_prompt] | |
| return pipe(**kwargs).images | |
| if __name__=='__main__': | |
| import argparse | |
| from PIL import Image | |
| p=argparse.ArgumentParser() | |
| p.add_argument('kind',choices=['characters','backgrounds']) | |
| text=p.add_mutually_exclusive_group() | |
| text.add_argument('--prompt',help='Complete prompt; overrides the warm-painted template.') | |
| text.add_argument('--description',help='Subject/location description; recommended warm-painted style is added.') | |
| p.add_argument('--negative-prompt',default='') | |
| p.add_argument('--reference',type=Path) | |
| p.add_argument('--steps',type=int,choices=[40,50],default=50) | |
| p.add_argument('--seed',type=int,default=28008) | |
| p.add_argument('--cfg-mode',choices=['sequential','batched','parallel'],default='batched') | |
| p.add_argument('--no-compile',action='store_true') | |
| p.add_argument('--base-path',type=Path) | |
| p.add_argument('--output',type=Path,default=ROOT/'native-preview.png') | |
| a=p.parse_args() | |
| pipe=create_native_pipeline(a.kind,compile_mode=None if a.no_compile else 'default',cfg_mode=a.cfg_mode,base_path=a.base_path) | |
| images=generate_native_image(pipe,a.prompt,a.seed,a.steps,negative_prompt=a.negative_prompt, | |
| image=Image.open(a.reference).convert('RGB') if a.reference else None,description=a.description) | |
| a.output.parent.mkdir(parents=True,exist_ok=True); images[0].save(a.output) | |
| print('Saved',a.output) | |