@@ -62,7 +62,7 @@ def partition_prompts(prompt_str: str, batch_size: int) -> List[str]:
6262 max_logging .log (
6363 f"⚠️ Warning: Found { num_prompts } prompts, but batch_size is { batch_size } . Truncating to the first { batch_size } ."
6464 )
65- return raw_prompts [: batch_size ]
65+
6666
6767
6868def encode_prompt (prompt : str , snapshot_dir : str = None , repo_id : str = "black-forest-labs/FLUX.2-klein-4B" ):
@@ -78,8 +78,18 @@ def encode_prompt(prompt: str, snapshot_dir: str = None, repo_id: str = "black-f
7878
7979 text_encoder_path = os .path .join (snapshot_dir , "text_encoder" )
8080 tokenizer_path = os .path .join (snapshot_dir , "tokenizer" )
81- if not os .path .exists (tokenizer_path ):
82- tokenizer_path = text_encoder_path
81+
82+ if not os .path .exists (os .path .join (text_encoder_path , "config.json" )) or not os .path .exists (tokenizer_path ):
83+ try :
84+ fb_dir = snapshot_download (repo_id = repo_id , local_files_only = True )
85+ if not os .path .exists (os .path .join (text_encoder_path , "config.json" )):
86+ text_encoder_path = os .path .join (fb_dir , "text_encoder" )
87+ if not os .path .exists (tokenizer_path ):
88+ tokenizer_path = os .path .join (fb_dir , "tokenizer" ) if os .path .exists (os .path .join (fb_dir , "tokenizer" )) else os .path .join (fb_dir , "text_encoder" )
89+ except Exception as e :
90+ if not os .path .exists (tokenizer_path ):
91+ tokenizer_path = text_encoder_path
92+
8393 tokenizer = AutoTokenizer .from_pretrained (tokenizer_path )
8494 text_encoder = AutoModelForCausalLM .from_pretrained (text_encoder_path , torch_dtype = torch .float32 )
8595 text_encoder .eval ()
@@ -183,8 +193,13 @@ def main(argv):
183193 else :
184194 from huggingface_hub import snapshot_download
185195
186- max_logging .log (f"Resolving snapshot directory for model '{ repo_id } ' from HF Hub..." )
187- snapshot_dir = snapshot_download (repo_id = repo_id )
196+ rev = getattr (config , "revision" , None )
197+ if not rev or rev == "refs/pr/95" :
198+ rev = "main"
199+ try :
200+ snapshot_dir = snapshot_download (repo_id = repo_id , revision = rev , local_files_only = True )
201+ except Exception :
202+ snapshot_dir = snapshot_download (repo_id = repo_id , local_files_only = True )
188203
189204 max_logging .log (f"Host { jax .process_index ()} using HF snapshot directory: { snapshot_dir } " )
190205 safetensors_path = os .path .join (snapshot_dir , "transformer" )
@@ -194,8 +209,13 @@ def main(argv):
194209 # 4. Load Qwen3 Config & Setup model layout
195210 from transformers import AutoConfig
196211
197- max_logging .log (f"Loading Qwen3 config from text_encoder path: { text_encoder_path } ..." )
198- pt_config = AutoConfig .from_pretrained (text_encoder_path , local_files_only = True )
212+ try :
213+ pt_config = AutoConfig .from_pretrained (text_encoder_path , local_files_only = True )
214+ except Exception as e :
215+ depth_val = getattr (config , "depth" , 24 )
216+ hf_repo = "black-forest-labs/FLUX.2-klein-9B" if depth_val in (24 , - 1 ) else "black-forest-labs/FLUX.2-klein-4B"
217+ max_logging .log (f"ℹ️ Config not found in { text_encoder_path } . Resolving from HF cache: { hf_repo } " )
218+ pt_config = AutoConfig .from_pretrained (hf_repo , subfolder = "text_encoder" , local_files_only = True )
199219
200220 qwen3_config = FlaxQwen3Config (
201221 vocab_size = pt_config .vocab_size ,
@@ -216,9 +236,25 @@ def main(argv):
216236
217237 transformer_config_json = os .path .join (safetensors_path , "config.json" )
218238 transformer_pt_cfg = {}
239+ loaded_cfg = False
219240 if os .path .exists (transformer_config_json ):
220- with open (transformer_config_json , "r" ) as f :
221- transformer_pt_cfg = json .load (f )
241+ try :
242+ with open (transformer_config_json , "r" ) as f :
243+ transformer_pt_cfg = json .load (f )
244+ loaded_cfg = True
245+ except Exception as e :
246+ max_logging .log (f"ℹ️ Could not parse { transformer_config_json } : { e } . Falling back to HF cache..." )
247+
248+ if not loaded_cfg :
249+ depth_val = getattr (config , "depth" , 24 )
250+ hf_repo = "black-forest-labs/FLUX.2-klein-9B" if depth_val in (24 , - 1 ) else "black-forest-labs/FLUX.2-klein-4B"
251+ try :
252+ from huggingface_hub import hf_hub_download
253+ cfg_file = hf_hub_download (repo_id = hf_repo , filename = "transformer/config.json" , local_files_only = True )
254+ with open (cfg_file , "r" ) as f :
255+ transformer_pt_cfg = json .load (f )
256+ except Exception as e :
257+ max_logging .log (f"⚠️ Warning resolving transformer config fallback: { e } " )
222258
223259 num_double_layers = getattr (config , "num_double_layers" , - 1 )
224260 if num_double_layers is None or num_double_layers <= 0 :
@@ -481,9 +517,22 @@ def unbox_fn(x):
481517 max_logging .log (f" -> Custom latents shape: { latents_to_use .shape } | sum: { latents_to_use .sum ():.6f} " )
482518
483519 max_logging .log ("\n " + "=" * 80 )
484- max_logging .log ("🚀 Running initial dry run (Warmup Pass) to compile XLA graphs..." )
520+ max_logging .log ("🚀 Pre-compiling XLA graphs concurrently (AOT Compilation)..." )
521+ max_logging .log ("=" * 80 )
522+ aot_time = pipeline .compile_aot_async (
523+ params = params ,
524+ vae_params = vae_params ,
525+ qwen3_params = qwen3_params ,
526+ vae_bn_mean = vae_bn_mean ,
527+ vae_bn_std = vae_bn_std ,
528+ batch_size = config .batch_size ,
529+ height = config .height ,
530+ width = config .width ,
531+ )
532+
533+ max_logging .log ("\n " + "=" * 80 )
534+ max_logging .log ("🚀 Running initial dry run (Warmup Pass) to verify compiled graph execution..." )
485535 max_logging .log ("=" * 80 )
486- pipeline .compile_aot_async (params , vae_params , qwen3_params , batch_size = config .batch_size , height = config .height , width = config .width )
487536 _ , warmup_trace = pipeline (
488537 prompt = active_prompts ,
489538 params = params ,
@@ -500,7 +549,6 @@ def unbox_fn(x):
500549 batch_size = config .batch_size ,
501550 use_latents = use_latents_flag ,
502551 latents = latents_to_use ,
503- warmup = True ,
504552 output_dir = config .output_dir ,
505553 output_name = "flux2klein_warmup.png" ,
506554 )
@@ -536,15 +584,19 @@ def unbox_fn(x):
536584 main_trace .get ("prompt_encoding" , 0.0 ) + main_trace .get ("denoise_loop" , 0.0 ) + main_trace .get ("vae_decode" , 0.0 )
537585 )
538586
587+ total_cold_start = load_time + aot_time + warmup_time
588+
539589 max_logging .log ("\n " + "=" * 80 )
540- max_logging .log ("📊 FLUX.2-KLEIN LATENCY & TIMING BREAKDOWN (PURE MODEL INFERENCE) " )
590+ max_logging .log ("📊 FLUX.2-KLEIN COMPLETE LATENCY & TIMING BREAKDOWN" )
541591 max_logging .log ("=" * 80 )
542- max_logging .log (f"1) Total Model Loading & Placement Time: { load_time :.2f} seconds ⏱️" )
543- max_logging .log (f"2) Cold-Start / Warmup Pass (XLA Compilation): { warmup_time :.2f} seconds ⏱️" )
592+ max_logging .log (f"1) Model Loading & Placement Time: { load_time :.2f} seconds ⏱️" )
593+ max_logging .log (f"2) Concurrent AOT XLA Compilation Time: { aot_time :.2f} seconds ⚡" )
594+ max_logging .log (f"3) Warmup Pass Execution Time: { warmup_time :.2f} seconds ⏱️" )
544595 max_logging .log (f" - Qwen3 Encoding: { warmup_trace .get ('prompt_encoding' , 0.0 ):.2f} s" )
545596 max_logging .log (f" - Flux Denoising: { warmup_trace .get ('denoise_loop' , 0.0 ):.2f} s" )
546597 max_logging .log (f" - VAE Decoding: { warmup_trace .get ('vae_decode' , 0.0 ):.2f} s" )
547- max_logging .log (f"3) Main Warmed-Up Pass (Pure Model Inference): { main_time :.2f} seconds ⏱️" )
598+ max_logging .log (f"👉 TOTAL COLD-START TIME (Loading + AOT + Warmup): { total_cold_start :.2f} seconds 🎯" )
599+ max_logging .log (f"4) Main Warmed-Up Pass (Pure Inference Latency): { main_time :.2f} seconds ⏱️" )
548600 max_logging .log (f" - Qwen3 Encoding: { main_trace .get ('prompt_encoding' , 0.0 ):.2f} s" )
549601 max_logging .log (f" - Flux Denoising: { main_trace .get ('denoise_loop' , 0.0 ):.2f} s" )
550602 max_logging .log (f" - VAE Decoding: { main_trace .get ('vae_decode' , 0.0 ):.2f} s" )
0 commit comments