diff --git a/src/maxdiffusion/configs/base_flux2klein.yml b/src/maxdiffusion/configs/base_flux2klein.yml index f2813c8fd..033e8a578 100644 --- a/src/maxdiffusion/configs/base_flux2klein.yml +++ b/src/maxdiffusion/configs/base_flux2klein.yml @@ -203,7 +203,7 @@ num_train_epochs: 1 seed: 0 output_dir: 'output/' output_name: "flux2klein_generated_image.png" -per_device_batch_size: 1 +per_device_batch_size: 1.0 warmup_steps_fraction: 0.1 learning_rate_schedule_steps: -1 # By default the length of the schedule is set to the number of steps. @@ -231,6 +231,7 @@ do_classifier_free_guidance: True guidance_scale: 4.0 guidance_rescale: 0.0 num_inference_steps: 4 +num_reps: 1 save_final_checkpoint: False # SDXL Lightning parameters diff --git a/src/maxdiffusion/configs/base_flux2klein_9B.yml b/src/maxdiffusion/configs/base_flux2klein_9B.yml index a6c670a69..669a1c29e 100644 --- a/src/maxdiffusion/configs/base_flux2klein_9B.yml +++ b/src/maxdiffusion/configs/base_flux2klein_9B.yml @@ -203,7 +203,7 @@ num_train_epochs: 1 seed: 0 output_dir: 'output/' output_name: "flux2klein_generated_image.png" -per_device_batch_size: 1 +per_device_batch_size: 1.0 warmup_steps_fraction: 0.1 learning_rate_schedule_steps: -1 # By default the length of the schedule is set to the number of steps. @@ -231,6 +231,7 @@ do_classifier_free_guidance: True guidance_scale: 4.0 guidance_rescale: 0.0 num_inference_steps: 4 +num_reps: 1 save_final_checkpoint: False # SDXL Lightning parameters diff --git a/src/maxdiffusion/generate_flux2klein.py b/src/maxdiffusion/generate_flux2klein.py index 7956c850d..caeb9f171 100644 --- a/src/maxdiffusion/generate_flux2klein.py +++ b/src/maxdiffusion/generate_flux2klein.py @@ -79,8 +79,22 @@ def encode_prompt(prompt: str, snapshot_dir: str = None, repo_id: str = "black-f text_encoder_path = os.path.join(snapshot_dir, "text_encoder") tokenizer_path = os.path.join(snapshot_dir, "tokenizer") - if not os.path.exists(tokenizer_path): - tokenizer_path = text_encoder_path + + if not os.path.exists(os.path.join(text_encoder_path, "config.json")) or not os.path.exists(tokenizer_path): + try: + fb_dir = snapshot_download(repo_id=repo_id, local_files_only=True) + if not os.path.exists(os.path.join(text_encoder_path, "config.json")): + text_encoder_path = os.path.join(fb_dir, "text_encoder") + if not os.path.exists(tokenizer_path): + 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") + ) + except Exception: + if not os.path.exists(tokenizer_path): + tokenizer_path = text_encoder_path + tokenizer = AutoTokenizer.from_pretrained(tokenizer_path) text_encoder = AutoModelForCausalLM.from_pretrained(text_encoder_path, torch_dtype=torch.float32) text_encoder.eval() @@ -134,15 +148,28 @@ def main(argv): from maxdiffusion.models.flux.util import ( load_and_convert_flux_klein_weights, load_and_convert_vae_weights, - cast_dict_to_bfloat16_inplace, ) from maxdiffusion.pipelines.flux.flux2klein_pipeline import FlaxFlux2KleinPipeline config = pyconfig.config os.makedirs(config.output_dir, exist_ok=True) + if hasattr(config, "per_device_batch_size") and config.per_device_batch_size > 0: + calculated_batch_size = int(config.per_device_batch_size * jax.device_count()) + if calculated_batch_size != config.batch_size: + max_logging.log( + f"ℹ️ Updating batch_size from {config.batch_size} to {calculated_batch_size} " + f"based on per_device_batch_size={config.per_device_batch_size} and device_count={jax.device_count()}." + ) + pyconfig._config.keys["batch_size"] = calculated_batch_size + # 2. Setup device mesh - if config.batch_size == 1 and config.ici_tensor_parallelism == 1 and jax.device_count() > 1: + if ( + config.batch_size == 1 + and config.ici_tensor_parallelism == 1 + and config.ici_context_parallelism == 1 + and jax.device_count() > 1 + ): max_logging.log( f"ℹ️ Auto-configuring Tensor Parallelism: ici_tensor_parallelism={jax.device_count()}, ici_fsdp_parallelism=1 for batch_size=1 on {jax.device_count()} TPU devices." ) @@ -184,8 +211,16 @@ def main(argv): else: from huggingface_hub import snapshot_download - max_logging.log(f"Resolving snapshot directory for model '{repo_id}' from HF Hub...") - snapshot_dir = snapshot_download(repo_id=repo_id) + rev = getattr(config, "revision", None) + if not rev or rev == "refs/pr/95": + rev = "main" + try: + snapshot_dir = snapshot_download(repo_id=repo_id, revision=rev, local_files_only=True) + except Exception: + try: + snapshot_dir = snapshot_download(repo_id=repo_id, local_files_only=True) + except Exception: + snapshot_dir = snapshot_download(repo_id=repo_id) max_logging.log(f"Host {jax.process_index()} using HF snapshot directory: {snapshot_dir}") safetensors_path = os.path.join(snapshot_dir, "transformer") @@ -195,8 +230,13 @@ def main(argv): # 4. Load Qwen3 Config & Setup model layout from transformers import AutoConfig - max_logging.log(f"Loading Qwen3 config from text_encoder path: {text_encoder_path}...") - pt_config = AutoConfig.from_pretrained(text_encoder_path, local_files_only=True) + try: + pt_config = AutoConfig.from_pretrained(text_encoder_path, local_files_only=True) + except Exception: + depth_val = getattr(config, "depth", 24) + hf_repo = "black-forest-labs/FLUX.2-klein-9B" if depth_val in (24, -1) else "black-forest-labs/FLUX.2-klein-4B" + max_logging.log(f"ℹ️ Config not found in {text_encoder_path}. Resolving from HF cache: {hf_repo}") + pt_config = AutoConfig.from_pretrained(hf_repo, subfolder="text_encoder", local_files_only=True) qwen3_config = FlaxQwen3Config( vocab_size=pt_config.vocab_size, @@ -217,9 +257,26 @@ def main(argv): transformer_config_json = os.path.join(safetensors_path, "config.json") transformer_pt_cfg = {} + loaded_cfg = False if os.path.exists(transformer_config_json): - with open(transformer_config_json, "r") as f: - transformer_pt_cfg = json.load(f) + try: + with open(transformer_config_json, "r") as f: + transformer_pt_cfg = json.load(f) + loaded_cfg = True + except Exception as e: + max_logging.log(f"ℹ️ Could not parse {transformer_config_json}: {e}. Falling back to HF cache...") + + if not loaded_cfg: + depth_val = getattr(config, "depth", 24) + hf_repo = "black-forest-labs/FLUX.2-klein-9B" if depth_val in (24, -1) else "black-forest-labs/FLUX.2-klein-4B" + try: + from huggingface_hub import hf_hub_download + + cfg_file = hf_hub_download(repo_id=hf_repo, filename="transformer/config.json", local_files_only=True) + with open(cfg_file, "r") as f: + transformer_pt_cfg = json.load(f) + except Exception as e: + max_logging.log(f"⚠️ Warning resolving transformer config fallback: {e}") num_double_layers = getattr(config, "num_double_layers", -1) if num_double_layers is None or num_double_layers <= 0: @@ -342,6 +399,7 @@ def qwen3_init_fn(): def unbox_fn(x): return x.unbox() if isinstance(x, flax_spmd.LogicallyPartitioned) else x + t_sub0 = time.time() params = jax.tree_util.tree_map( unbox_fn, abstract_transformer_vars["params"], is_leaf=lambda k: isinstance(k, flax_spmd.LogicallyPartitioned) ) @@ -357,17 +415,19 @@ def unbox_fn(x): ) qwen3_params = flax.core.unfreeze(qwen3_params) - params = load_and_convert_flux_klein_weights(safetensors_path, params, num_double_layers, depth) - vae_params, vae_bn_mean, vae_bn_std = load_and_convert_vae_weights(vae_safetensors_path, vae_params) - qwen3_params = load_and_convert_qwen3_weights(text_encoder_path, qwen3_params, qwen3_config) + max_logging.log(f" -> [SUB-TIMING 1/3] PyTree unboxing template setup: {time.time() - t_sub0:.2f}s") + t_sub1 = time.time() + + weight_dtype = jnp.bfloat16 if config.weights_dtype == "bfloat16" else jnp.float32 - if config.weights_dtype == "bfloat16": - max_logging.log("Casting JAX parameters to bfloat16 in-place...") - cast_dict_to_bfloat16_inplace(params, exclude_keywords=("norm",)) - cast_dict_to_bfloat16_inplace(vae_params, exclude_keywords=("norm",)) - cast_dict_to_bfloat16_inplace(qwen3_params, exclude_keywords=("norm",)) - vae_bn_mean = vae_bn_mean.astype(jnp.bfloat16) - vae_bn_std = vae_bn_std.astype(jnp.bfloat16) + params = load_and_convert_flux_klein_weights(safetensors_path, params, num_double_layers, depth, dtype=weight_dtype) + vae_params, vae_bn_mean, vae_bn_std = load_and_convert_vae_weights( + vae_safetensors_path, vae_params, dtype=weight_dtype + ) + qwen3_params = load_and_convert_qwen3_weights(text_encoder_path, qwen3_params, qwen3_config) + max_logging.log( + f" -> [SUB-TIMING 2/3] Safetensors loading & key mapping (in target dtype): {time.time() - t_sub1:.4f}s" + ) params = flax.core.freeze(params) vae_params = flax.core.freeze(vae_params) @@ -376,6 +436,7 @@ def unbox_fn(x): max_logging.log("\n" + "=" * 80) max_logging.log("🚀 Pinning all parameters to TPU HBM permanently...") max_logging.log("=" * 80 + "\n") + t_sub3 = time.time() max_logging.log("Putting params on TPU HBM...") with mesh, nn_partitioning.axis_rules(config.logical_axis_rules): try: @@ -394,12 +455,13 @@ def unbox_fn(x): vae_params = jax.tree_util.tree_map(max_utils.device_put_replicated, vae_params, vae_shardings) max_logging.log("Putting qwen3_params on TPU HBM...") qwen3_params = jax.tree_util.tree_map(max_utils.device_put_replicated, qwen3_params, qwen3_shardings) + max_logging.log(f" -> [SUB-TIMING 3/3] TPU HBM device_put placement: {time.time() - t_sub3:.4f}s") max_logging.log("All parameters placed on TPU HBM successfully!") gc.collect() jax.effects_barrier() load_time = time.time() - t_load_start - max_logging.log(f" -> [TIMING] Total Model Loading & Device Placement: {load_time:.2f} seconds ⏱️\n") + max_logging.log(f" -> [TIMING] Total Model Loading & Device Placement: {load_time:.4f} seconds ⏱️\n") # 9. Setup FlowMatch Scheduler scheduler = FlaxFlowMatchScheduler( @@ -426,16 +488,17 @@ def unbox_fn(x): mesh=mesh, ) - active_prompts = partition_prompts(config.prompt, config.batch_size) + prompt_str = getattr(config, "prompt", "") or "A dog running in a field with butterflies and tall grass" + active_prompts = partition_prompts(prompt_str, config.batch_size) if getattr(config, "interactive", False): - print("\n" + "=" * 80) - print(" BATCHED INTERACTIVE GENERATION MODE ENABLED 🎮") - print("The model has been fully loaded and compiled on the TPU.") - print(f"Batch size: {config.batch_size} parallel images.") - print("Enter prompts separated by '||' (e.g. A cute cat || A red car)") - print("Type 'exit' to quit.") - print("=" * 80) + max_logging.log("\n" + "=" * 80) + max_logging.log(" BATCHED INTERACTIVE GENERATION MODE ENABLED 🎮") + max_logging.log("The model has been fully loaded and compiled on the TPU.") + max_logging.log(f"Batch size: {config.batch_size} parallel images.") + max_logging.log("Enter prompts separated by '||' (e.g. A cute cat || A red car)") + max_logging.log("Type 'exit' to quit.") + max_logging.log("=" * 80) image_idx = 1 while True: @@ -481,37 +544,23 @@ def unbox_fn(x): max_logging.log(f" -> Custom latents shape: {latents_to_use.shape} | sum: {latents_to_use.sum():.6f}") max_logging.log("\n" + "=" * 80) - max_logging.log("🚀 Running initial dry run (Warmup Pass) to compile XLA graphs...") + max_logging.log("🚀 Pre-compiling XLA graphs concurrently (AOT Compilation)...") max_logging.log("=" * 80) - _, warmup_trace = pipeline( - prompt=active_prompts, + aot_time = pipeline.compile_aot_async( params=params, vae_params=vae_params, qwen3_params=qwen3_params, vae_bn_mean=vae_bn_mean, vae_bn_std=vae_bn_std, - transformer_shardings=transformer_shardings, - vae_shardings=vae_shardings, - qwen3_shardings=qwen3_shardings, + batch_size=config.batch_size, height=config.height, width=config.width, - num_inference_steps=config.num_inference_steps, - batch_size=config.batch_size, - use_latents=use_latents_flag, - latents=latents_to_use, - output_dir=config.output_dir, - output_name="flux2klein_warmup.png", - ) - warmup_time = ( - warmup_trace.get("prompt_encoding", 0.0) - + warmup_trace.get("denoise_loop", 0.0) - + warmup_trace.get("vae_decode", 0.0) ) max_logging.log("\n" + "=" * 80) - max_logging.log("⏱️ Running timed pass at full TPU speed...") + max_logging.log("🚀 Running initial dry run (Warmup Pass) to verify compiled graph execution...") max_logging.log("=" * 80) - _, main_trace = pipeline( + _, warmup_trace = pipeline( prompt=active_prompts, params=params, vae_params=vae_params, @@ -528,24 +577,101 @@ def unbox_fn(x): use_latents=use_latents_flag, latents=latents_to_use, output_dir=config.output_dir, - output_name=config.output_name, + output_name="flux2klein_warmup.png", + warmup=True, ) - main_time = ( - main_trace.get("prompt_encoding", 0.0) + main_trace.get("denoise_loop", 0.0) + main_trace.get("vae_decode", 0.0) + warmup_time = ( + warmup_trace.get("prompt_encoding", 0.0) + + warmup_trace.get("denoise_loop", 0.0) + + warmup_trace.get("vae_decode", 0.0) ) + num_reps = int(getattr(config, "num_reps", 1)) + max_logging.log("\n" + "=" * 80) + max_logging.log(f"⏱️ Running timed pass at full TPU speed (num_reps={num_reps})...") + max_logging.log("=" * 80) + + main_traces = [] + main_times = [] + + for rep in range(num_reps): + rep_str = f" [Rep {rep+1}/{num_reps}]" if num_reps > 1 else "" + if rep > 0: + max_logging.log(f"⏱️ Running timed pass{rep_str}...") + + if max_utils.profiler_enabled(config) and rep == 0: + max_logging.log(f"🚀 XProf / JAX Profiler active! Capturing trace into: {config.tensorboard_dir}") + with max_utils.Profiler(config, session_name="flux2klein_inference"): + _, trace_i = pipeline( + prompt=active_prompts, + params=params, + vae_params=vae_params, + qwen3_params=qwen3_params, + vae_bn_mean=vae_bn_mean, + vae_bn_std=vae_bn_std, + transformer_shardings=transformer_shardings, + vae_shardings=vae_shardings, + qwen3_shardings=qwen3_shardings, + height=config.height, + width=config.width, + num_inference_steps=config.num_inference_steps, + batch_size=config.batch_size, + use_latents=use_latents_flag, + latents=latents_to_use, + output_dir=config.output_dir, + output_name=f"rep_{rep+1}_{config.output_name}" if num_reps > 1 else config.output_name, + ) + else: + _, trace_i = pipeline( + prompt=active_prompts, + params=params, + vae_params=vae_params, + qwen3_params=qwen3_params, + vae_bn_mean=vae_bn_mean, + vae_bn_std=vae_bn_std, + transformer_shardings=transformer_shardings, + vae_shardings=vae_shardings, + qwen3_shardings=qwen3_shardings, + height=config.height, + width=config.width, + num_inference_steps=config.num_inference_steps, + batch_size=config.batch_size, + use_latents=use_latents_flag, + latents=latents_to_use, + output_dir=config.output_dir, + output_name=f"rep_{rep+1}_{config.output_name}" if num_reps > 1 else config.output_name, + ) + + tot_time_i = trace_i.get("prompt_encoding", 0.0) + trace_i.get("denoise_loop", 0.0) + trace_i.get("vae_decode", 0.0) + main_traces.append(trace_i) + main_times.append(tot_time_i) + if num_reps > 1: + max_logging.log( + f" -> Rep {rep+1}/{num_reps} Completed: Total={tot_time_i:.4f}s | Qwen3={trace_i.get('prompt_encoding', 0.0):.4f}s | Denoise={trace_i.get('denoise_loop', 0.0):.4f}s | VAE={trace_i.get('vae_decode', 0.0):.4f}s" + ) + + avg_main_time = sum(main_times) / num_reps + avg_prompt_enc = sum(tr.get("prompt_encoding", 0.0) for tr in main_traces) / num_reps + avg_denoise = sum(tr.get("denoise_loop", 0.0) for tr in main_traces) / num_reps + avg_vae_decode = sum(tr.get("vae_decode", 0.0) for tr in main_traces) / num_reps + + total_cold_start = load_time + aot_time + warmup_time + max_logging.log("\n" + "=" * 80) - max_logging.log("📊 FLUX.2-KLEIN LATENCY & TIMING BREAKDOWN (PURE MODEL INFERENCE)") + max_logging.log("📊 FLUX.2-KLEIN COMPLETE LATENCY & TIMING BREAKDOWN") max_logging.log("=" * 80) - max_logging.log(f"1) Total Model Loading & Placement Time: {load_time:.2f} seconds ⏱️") - max_logging.log(f"2) Cold-Start / Warmup Pass (XLA Compilation): {warmup_time:.2f} seconds ⏱️") - max_logging.log(f" - Qwen3 Encoding: {warmup_trace.get('prompt_encoding', 0.0):.2f}s") - max_logging.log(f" - Flux Denoising: {warmup_trace.get('denoise_loop', 0.0):.2f}s") - max_logging.log(f" - VAE Decoding: {warmup_trace.get('vae_decode', 0.0):.2f}s") - max_logging.log(f"3) Main Warmed-Up Pass (Pure Model Inference): {main_time:.2f} seconds ⏱️") - max_logging.log(f" - Qwen3 Encoding: {main_trace.get('prompt_encoding', 0.0):.2f}s") - max_logging.log(f" - Flux Denoising: {main_trace.get('denoise_loop', 0.0):.2f}s") - max_logging.log(f" - VAE Decoding: {main_trace.get('vae_decode', 0.0):.2f}s") + max_logging.log(f"1) Model Loading & Placement Time: {load_time:.4f} seconds ⏱️") + max_logging.log(f"2) Concurrent AOT XLA Compilation Time: {aot_time:.4f} seconds ⚡") + max_logging.log(f"3) Warmup Pass Execution Time: {warmup_time:.4f} seconds ⏱️") + max_logging.log(f" - Qwen3 Encoding: {warmup_trace.get('prompt_encoding', 0.0):.4f}s") + max_logging.log(f" - Flux Denoising: {warmup_trace.get('denoise_loop', 0.0):.4f}s") + max_logging.log(f" - VAE Decoding: {warmup_trace.get('vae_decode', 0.0):.4f}s") + max_logging.log(f"👉 TOTAL COLD-START TIME (Loading + AOT + Warmup): {total_cold_start:.4f} seconds 🎯") + rep_label = f" (Average across {num_reps} reps)" if num_reps > 1 else "" + max_logging.log(f"4) Main Warmed-Up Pass (Pure Inference Latency){rep_label}: {avg_main_time:.4f} seconds ⏱️") + max_logging.log(f" - Qwen3 Encoding: {avg_prompt_enc:.4f}s") + max_logging.log(f" - Flux Denoising: {avg_denoise:.4f}s") + max_logging.log(f" - VAE Decoding: {avg_vae_decode:.4f}s") max_logging.log("=" * 80) max_logging.log("\n=======================================================") diff --git a/src/maxdiffusion/models/flux/util.py b/src/maxdiffusion/models/flux/util.py index 952519776..f7567e8cb 100644 --- a/src/maxdiffusion/models/flux/util.py +++ b/src/maxdiffusion/models/flux/util.py @@ -300,17 +300,17 @@ def unpack_latents(latents, batch_size, num_channels_latents, height, width): Unpacks packed sequence of shape (batch_size, (height//16)*(width//16), channels*4) back to the unpacked spatial grid shape (batch_size, channels, height//8, width//8). """ - import numpy as np + import jax.numpy as jnp h_latent = height // 8 w_latent = width // 8 # 1. Reshape to split spatial grid and packed channel blocks - latents = np.reshape(latents, (batch_size, h_latent // 2, w_latent // 2, num_channels_latents, 2, 2)) + latents = jnp.reshape(latents, (batch_size, h_latent // 2, w_latent // 2, num_channels_latents, 2, 2)) # 2. Permute dimensions back to unpacked order - latents = np.transpose(latents, (0, 3, 1, 4, 2, 5)) + latents = jnp.transpose(latents, (0, 3, 1, 4, 2, 5)) # 3. Flatten back to 4D unpacked latent shape - latents = np.reshape(latents, (batch_size, num_channels_latents, h_latent, w_latent)) + latents = jnp.reshape(latents, (batch_size, num_channels_latents, h_latent, w_latent)) return latents @@ -398,11 +398,12 @@ def cast_dict_to_bfloat16_inplace(d, device=None, exclude_keywords=None, parent_ is_excluded = exclude_keywords and any(kw.lower() in current_key.lower() for kw in exclude_keywords) target_dtype = jnp.float32 if is_excluded else jnp.bfloat16 - d[k] = v.astype(target_dtype) - if hasattr(d[k], "block_until_ready"): - d[k].block_until_ready() - del v - gc.collect() + if v.dtype != target_dtype: + d[k] = v.astype(target_dtype) + if hasattr(d[k], "block_until_ready"): + d[k].block_until_ready() + del v + gc.collect() # ----------------------------------------------------------------------------- @@ -410,7 +411,9 @@ def cast_dict_to_bfloat16_inplace(d, device=None, exclude_keywords=None, parent_ # ----------------------------------------------------------------------------- -def load_and_convert_flux_klein_weights(safetensors_path, params, num_double_layers, num_single_layers): +def load_and_convert_flux_klein_weights( + safetensors_path, params, num_double_layers, num_single_layers, dtype=None, pt_state_dict=None +): """ Loads weights from safetensors via zero-copy safetensors.numpy and converts them to JAX parameter dictionary. Supports dynamic layer counts (double and single stream blocks) and sharded safetensors directories. @@ -422,28 +425,30 @@ def load_and_convert_flux_klein_weights(safetensors_path, params, num_double_lay import os import gc - pt_state_dict = {} - if os.path.isdir(safetensors_path): - shards = glob.glob(os.path.join(safetensors_path, "*.safetensors")) - max_logging.log(f"Loading sharded weights from directory: {safetensors_path} (Found {len(shards)} shards)...") - for shard in sorted(shards): - max_logging.log(f"Loading shard: {shard}...") - pt_state_dict.update(load_file(shard)) - else: - max_logging.log(f"Loading weights from: {safetensors_path}") - pt_state_dict = load_file(safetensors_path) + if pt_state_dict is None: + pt_state_dict = {} + if os.path.isdir(safetensors_path): + shards = glob.glob(os.path.join(safetensors_path, "*.safetensors")) + max_logging.log(f"Loading sharded weights from directory: {safetensors_path} (Found {len(shards)} shards)...") + for shard in sorted(shards): + max_logging.log(f"Loading shard: {shard}...") + pt_state_dict.update(load_file(shard)) + else: + max_logging.log(f"Loading weights from: {safetensors_path}") + pt_state_dict = load_file(safetensors_path) max_logging.log("Mapping weights to JAX parameters...") expected_pytree = jax.tree_util.tree_map(lambda leaf: leaf, params) first_leaf = jax.tree_util.tree_leaves(params)[0] - target_dtype = first_leaf.dtype + target_dtype = dtype if dtype is not None else first_leaf.dtype - def convert_and_transpose_tensor(tensor, transpose=False): + def convert_and_transpose_tensor(tensor, transpose=False, is_norm=False): if transpose and len(tensor.shape) == 2: tensor = tensor.T - return jnp.array(tensor, dtype=target_dtype) + leaf_dtype = jnp.float32 if is_norm else target_dtype + return jnp.array(tensor, dtype=leaf_dtype) # Global layers params["context_embedder"]["kernel"] = convert_and_transpose_tensor( @@ -562,21 +567,28 @@ def convert_and_transpose_tensor(tensor, transpose=False): return params -def load_and_convert_vae_weights(safetensors_path, jax_params): +def load_and_convert_vae_weights(safetensors_path, jax_params, dtype=None, pt_state_dict=None): """Loads VAE weights from safetensors via zero-copy safetensors.numpy, maps them to JAX, and extracts BN stats.""" from safetensors.numpy import load_file import flax import jax.numpy as jnp - max_logging.log(f"Loading VAE weights from: {safetensors_path}") - pt_state_dict = load_file(safetensors_path) - - def get_pytorch_weight_tensor(key): - return pt_state_dict[key] + if pt_state_dict is None: + max_logging.log(f"Loading VAE weights from: {safetensors_path}") + pt_state_dict = load_file(safetensors_path) # Unfreeze JAX params so we can load the weights jax_params = flax.core.unfreeze(jax_params) + first_leaf = jax.tree_util.tree_leaves(jax_params)[0] + target_dtype = dtype if dtype is not None else first_leaf.dtype + + def get_pytorch_weight_tensor(key, dtype_val=target_dtype): + tensor = pt_state_dict[key] + is_norm = any(kw in key.lower() for kw in ("norm", "layernorm", "rmsnorm", "groupnorm")) + leaf_dtype = jnp.float32 if is_norm else dtype_val + return jnp.array(tensor, dtype=leaf_dtype) + # Map weights max_logging.log("Mapping VAE decoder weights to JAX parameters...") diff --git a/src/maxdiffusion/models/resnet_flax.py b/src/maxdiffusion/models/resnet_flax.py index 79ddcb30e..8371a4432 100644 --- a/src/maxdiffusion/models/resnet_flax.py +++ b/src/maxdiffusion/models/resnet_flax.py @@ -57,9 +57,8 @@ def setup(self): @nn.compact def __call__(self, hidden_states): batch, height, width, channels = hidden_states.shape - hidden_states = jax.image.resize( - hidden_states, shape=(batch, height * 2, width * 2, channels), method="nearest", precision=self.precision - ) + hidden_states = jnp.broadcast_to(hidden_states[:, :, None, :, None, :], (batch, height, 2, width, 2, channels)) + hidden_states = jnp.reshape(hidden_states, (batch, height * 2, width * 2, channels)) hidden_states = nn.with_logical_constraint(hidden_states, ("conv_batch", "height", "keep_2", "out_channels")) diff --git a/src/maxdiffusion/models/vae_flax.py b/src/maxdiffusion/models/vae_flax.py index 72adcbe79..af13327bf 100644 --- a/src/maxdiffusion/models/vae_flax.py +++ b/src/maxdiffusion/models/vae_flax.py @@ -87,11 +87,8 @@ def setup(self): def __call__(self, hidden_states): batch, height, width, channels = hidden_states.shape - hidden_states = jax.image.resize( - hidden_states, - shape=(batch, height * 2, width * 2, channels), - method="nearest", - ) + hidden_states = jnp.broadcast_to(hidden_states[:, :, None, :, None, :], (batch, height, 2, width, 2, channels)) + hidden_states = jnp.reshape(hidden_states, (batch, height * 2, width * 2, channels)) hidden_states = self.conv(hidden_states) return hidden_states diff --git a/src/maxdiffusion/pipelines/flux/flux2klein_pipeline.py b/src/maxdiffusion/pipelines/flux/flux2klein_pipeline.py index 634ec8d9e..b109eb7c8 100644 --- a/src/maxdiffusion/pipelines/flux/flux2klein_pipeline.py +++ b/src/maxdiffusion/pipelines/flux/flux2klein_pipeline.py @@ -31,13 +31,12 @@ from maxdiffusion.max_utils import device_put_replicated from ..pipeline_flax_utils import FlaxDiffusionPipeline from ...models.flux.transformers.transformer_flux_flax import Flux2KleinTransformer2DModel -from ...models.vae_flax import FlaxAutoencoderKL +from ...models.vae_flax import FlaxAutoencoderKL, FlaxDecoderOutput from ...models.qwen3_flax import FlaxQwen3Model from ...schedulers.scheduling_flow_match_flax import FlaxFlowMatchScheduler, compute_empirical_mu from ...models.flux.util import ( pack_latents, - unpack_latents, prepare_latent_image_ids, prepare_text_ids, ) @@ -70,6 +69,7 @@ def __init__( ) self._config = config self.mesh = mesh + self.tokenizer = tokenizer # JIT compilation cache self._jitted_qwen3_forward = None @@ -97,14 +97,111 @@ def transformer_step(t_params, latents, img_ids, prompt_embeds, txt_ids, vec, ti guidance=guidance, ) - @jax.jit - def vae_decode(v_params, latents_unpatched): - return self.vae.apply({"params": v_params}, latents=latents_unpatched, method=self.vae.decode) + @jax.jit(static_argnums=(4, 5), donate_argnums=(1,)) + def vae_decode(v_params, latents_packed, vae_bn_mean, vae_bn_std, height, width): + def decode_single(single_latent): + vae_bn_mean_seq = vae_bn_mean.reshape(1, 1, 128) + vae_bn_std_seq = vae_bn_std.reshape(1, 1, 128) + latents_bn = single_latent.reshape(1, -1, 128) * vae_bn_std_seq + vae_bn_mean_seq + + h_latent = height // 8 + w_latent = width // 8 + latents_unpacked = jnp.reshape(latents_bn, (1, h_latent // 2, w_latent // 2, 32, 2, 2)) + latents_unpacked = jnp.transpose(latents_unpacked, (0, 3, 1, 4, 2, 5)) + latents_unpacked = jnp.reshape(latents_unpacked, (1, 32, h_latent, w_latent)) + + res = self.vae.apply({"params": v_params}, latents=latents_unpacked, method=self.vae.decode) + return res.sample[0] + + images = jax.vmap(decode_single)(latents_packed) + return FlaxDecoderOutput(sample=images) self._jitted_qwen3_forward = qwen3_forward self._jitted_transformer_step = transformer_step self._jitted_vae_decode = vae_decode + def _get_dynamic_batch_sharding(self): + """Dynamically infers the batch dimension sharding specification from self.mesh.""" + batch_axes = [axis for axis in ("data", "fsdp") if axis in self.mesh.axis_names and self.mesh.shape[axis] > 1] + spec = P(tuple(batch_axes)) if batch_axes else P(None) + return jax.sharding.NamedSharding(self.mesh, spec) + + def compile_aot_async( + self, params, vae_params, qwen3_params, vae_bn_mean, vae_bn_std, batch_size=1, height=1024, width=1024 + ): + """Triggers AOT compilation for Qwen3, Flux Transformer, and VAE concurrently using ThreadPoolExecutor.""" + self._setup_jit_functions() + max_logging.log("🚀 Pre-compiling XLA graphs for Qwen3, Flux Transformer, and VAE concurrently...") + from concurrent.futures import ThreadPoolExecutor + + seq_len_img = (height // 16) * (width // 16) + seq_len_txt = self._config.max_sequence_length + + dummy_ids = jnp.zeros((batch_size, seq_len_txt), dtype=jnp.int32) + dummy_mask = jnp.ones((batch_size, seq_len_txt), dtype=jnp.int32) + + dummy_latents = jnp.zeros((batch_size, seq_len_img, 128), dtype=jnp.float32) + dummy_img_ids = jnp.zeros((batch_size, seq_len_img, 4), dtype=jnp.int32) + dummy_prompt_embeds = jnp.zeros((batch_size, seq_len_txt, self.transformer.joint_attention_dim), dtype=jnp.bfloat16) + dummy_txt_ids = jnp.zeros((batch_size, seq_len_txt, 4), dtype=jnp.float32) + dummy_t_vec = jnp.zeros((batch_size,), dtype=jnp.float32) + + dummy_bn_mean = jnp.array(vae_bn_mean, dtype=jnp.float32) + dummy_bn_std = jnp.array(vae_bn_std, dtype=jnp.float32) + + data_sharding = self._get_dynamic_batch_sharding() + replicated_sharding = jax.sharding.NamedSharding(self.mesh, P()) + + def put_data_on_devices(x, sharding): + if isinstance(x, jax.Array) and hasattr(x, "sharding") and not x.sharding.is_fully_addressable: + return x + if hasattr(sharding, "is_fully_addressable") and sharding.is_fully_addressable: + return jax.device_put(x, sharding) + return device_put_replicated(x, sharding) + + dummy_ids = put_data_on_devices(dummy_ids, data_sharding) + dummy_mask = put_data_on_devices(dummy_mask, data_sharding) + dummy_latents = put_data_on_devices(dummy_latents, data_sharding) + dummy_img_ids = put_data_on_devices(dummy_img_ids, data_sharding) + dummy_prompt_embeds = put_data_on_devices(dummy_prompt_embeds, data_sharding) + dummy_txt_ids = put_data_on_devices(dummy_txt_ids, data_sharding) + dummy_t_vec = put_data_on_devices(dummy_t_vec, data_sharding) + dummy_bn_mean = put_data_on_devices(dummy_bn_mean, replicated_sharding) + dummy_bn_std = put_data_on_devices(dummy_bn_std, replicated_sharding) + + def compile_qwen3(): + t0 = time.perf_counter() + with self.mesh, nn_partitioning.axis_rules(self._config.logical_axis_rules): + self._jitted_qwen3_forward.lower(qwen3_params, dummy_ids, dummy_mask).compile() + max_logging.log(f" -> [AOT COMPILED] Qwen3 Text Encoder in {time.perf_counter() - t0:.2f}s") + + def compile_transformer(): + t0 = time.perf_counter() + with self.mesh, nn_partitioning.axis_rules(self._config.logical_axis_rules): + self._jitted_transformer_step.lower( + params, dummy_latents, dummy_img_ids, dummy_prompt_embeds, dummy_txt_ids, None, dummy_t_vec, None + ).compile() + max_logging.log(f" -> [AOT COMPILED] Flux Transformer Step in {time.perf_counter() - t0:.2f}s") + + def compile_vae(): + t0 = time.perf_counter() + with self.mesh, nn_partitioning.axis_rules(self._config.logical_axis_rules): + self._jitted_vae_decode.lower(vae_params, dummy_latents, dummy_bn_mean, dummy_bn_std, height, width).compile() + max_logging.log(f" -> [AOT COMPILED] VAE Decoder in {time.perf_counter() - t0:.2f}s") + + t_start = time.perf_counter() + with ThreadPoolExecutor(max_workers=3) as executor: + futures = [ + executor.submit(compile_qwen3), + executor.submit(compile_transformer), + executor.submit(compile_vae), + ] + for future in futures: + future.result() + aot_duration = time.perf_counter() - t_start + max_logging.log(f"⚡ [AOT CONCURRENT COMPILATION COMPLETE] Total AOT compile time: {aot_duration:.2f}s") + return aot_duration + def _prepare_latents(self, config, batch_size, height, width): num_channels_latents = 32 latent_height = height // 8 @@ -147,6 +244,7 @@ def __call__( use_latents: bool = False, latents: Optional[Any] = None, measure_time: bool = False, + warmup: bool = False, output_dir: str = "output/", output_name: str = "flux2klein_generated_image.png", ): @@ -199,18 +297,37 @@ def __call__( proc_cnt = jax.process_count() host_prefix = f"[HOST {proc_id}/{proc_cnt}] " + # Shard pipeline batch inputs across data axis ("data") for SPMD multi-host execution + data_sharding = jax.sharding.NamedSharding(self.mesh, P("data")) + + def put_data_on_devices(x, sharding): + if isinstance(x, jax.Array) and hasattr(x, "sharding") and not x.sharding.is_fully_addressable: + return x + if hasattr(sharding, "is_fully_addressable") and sharding.is_fully_addressable: + return jax.device_put(x, sharding) + return device_put_replicated(x, sharding) + # --------------------------------------------------------------------- # PHASE A: Encode Prompt (Qwen3) # --------------------------------------------------------------------- - print(f"{host_prefix} [PHASE A] Encoding {len(prompts)} prompt(s) using JAX Qwen3 on TPU...", flush=True) + if prompts is None: + prompts = ["A dog running in a field with butterflies and tall grass"] + elif isinstance(prompts, str): + prompts = [prompts] + + max_logging.log(f"{host_prefix} [PHASE A] Encoding {len(prompts)} prompt(s) using JAX Qwen3 on TPU...") t0 = time.perf_counter() try: - # Resolve tokenizer path from config - tokenizer_path = self._config.tokenizer_model_name_or_path + tokenizer_path = getattr(self._config, "tokenizer_model_name_or_path", None) or getattr( + self._config, "pretrained_model_name_or_path", "" + ) hf_home = os.environ.get("HF_HOME", os.path.expanduser("~/.cache/huggingface")) repo_cache = os.path.join( - hf_home, "hub", f"models--{self._config.pretrained_model_name_or_path.replace('/', '--')}", "snapshots" + hf_home, + "hub", + f"models--{getattr(self._config, 'pretrained_model_name_or_path', '').replace('/', '--')}", + "snapshots", ) if os.path.exists(repo_cache) and os.listdir(repo_cache): tokenizer_path = os.path.join(repo_cache, os.listdir(repo_cache)[0]) @@ -232,8 +349,11 @@ def __call__( prompt_ids = jnp.array(inputs["input_ids"]) prompt_mask = jnp.array(inputs["attention_mask"]) - # Run Text Encoding - hidden_states, all_hidden_states = self._jitted_qwen3_forward(qwen3_params, prompt_ids, prompt_mask) + # Run Text Encoding with sharded input arrays matching compile_aot_async + prompt_ids = put_data_on_devices(prompt_ids, data_sharding) + prompt_mask = put_data_on_devices(prompt_mask, data_sharding) + with jax.named_scope("qwen3_text_encoder"): + hidden_states, all_hidden_states = self._jitted_qwen3_forward(qwen3_params, prompt_ids, prompt_mask) # Stack layers 9, 18, 27 to form prompt embeddings h_9 = all_hidden_states[9] @@ -244,7 +364,7 @@ def __call__( prompt_embeds_jax = jnp.transpose(out, (0, 2, 1, 3)).reshape((batch_size, seq_len_txt, -1)) prompt_embeds_jax.block_until_ready() except Exception as e: - print(f"❌ {host_prefix} EXCEPTION IN PHASE A (QWEN3 ENCODING): {e}", flush=True) + max_logging.log(f"❌ {host_prefix} EXCEPTION IN PHASE A (QWEN3 ENCODING): {e}") import traceback traceback.print_exc() @@ -260,56 +380,49 @@ def __call__( # Stage Sync 1: Phase A Complete multihost_utils.sync_global_devices("phase_a_complete") - print(f"{host_prefix} Passed Phase A Sync Barrier (phase_a_complete) successfully! ✅", flush=True) - - # Shard pipeline batch inputs across data axis ("data") for SPMD multi-host execution - data_sharding = jax.sharding.NamedSharding(self.mesh, P("data")) - - def put_data_on_devices(x, sharding): - if isinstance(x, jax.Array) and hasattr(x, "sharding") and not x.sharding.is_fully_addressable: - return x - if hasattr(sharding, "is_fully_addressable") and sharding.is_fully_addressable: - return jax.device_put(x, sharding) - return device_put_replicated(x, sharding) + max_logging.log(f"{host_prefix} Passed Phase A Sync Barrier (phase_a_complete) successfully! ✅") latents_jax = put_data_on_devices(latents_jax, data_sharding) prompt_embeds_jax = put_data_on_devices(prompt_embeds_jax, data_sharding) txt_ids_val = put_data_on_devices(txt_ids_val, data_sharding) img_ids_val = put_data_on_devices(img_ids_val, data_sharding) - print( + max_logging.log( f"{host_prefix} DIAGNOSTIC TENSORS BEFORE PHASE B:\n" f" latents_jax: shape={latents_jax.shape}, dtype={latents_jax.dtype}, sharding={getattr(latents_jax, 'sharding', None)}\n" f" prompt_embeds_jax: shape={prompt_embeds_jax.shape}, dtype={prompt_embeds_jax.dtype}, sharding={getattr(prompt_embeds_jax, 'sharding', None)}\n" f" txt_ids_val: shape={txt_ids_val.shape}, dtype={txt_ids_val.dtype}, sharding={getattr(txt_ids_val, 'sharding', None)}\n" - f" img_ids_val: shape={img_ids_val.shape}, dtype={img_ids_val.dtype}, sharding={getattr(img_ids_val, 'sharding', None)}", - flush=True, + f" img_ids_val: shape={img_ids_val.shape}, dtype={img_ids_val.dtype}, sharding={getattr(img_ids_val, 'sharding', None)}" ) # Stage Sync 2: Pre-Phase B Start multihost_utils.sync_global_devices("pre_phase_b_start") - print(f"{host_prefix} Passed Pre-Phase B Sync Barrier (pre_phase_b_start) successfully! ✅", flush=True) + max_logging.log(f"{host_prefix} Passed Pre-Phase B Sync Barrier (pre_phase_b_start) successfully! ✅") # --------------------------------------------------------------------- # PHASE B: Denoising Loop (Flux Transformer - Standalone Step JIT) # --------------------------------------------------------------------- - print( - f"{host_prefix} [PHASE B] Running {num_inference_steps}-step E2E Denoising Loop on a batch of {batch_size} images...", - flush=True, + steps_to_run = 1 if warmup else num_inference_steps + max_logging.log( + f"{host_prefix} [PHASE B] Running {steps_to_run}-step E2E Denoising Loop on a batch of {batch_size} images (warmup={warmup})..." ) t0 = time.perf_counter() try: guidance_vec_val = None vec_val = None + active_latents_sharding = getattr(latents_jax, "sharding", data_sharding) - for step_idx in range(num_inference_steps): + for step_idx in range(steps_to_run): + t_step_start = time.perf_counter() timestep = scheduler_state.timesteps[step_idx] t_vec = jnp.full((batch_size,), timestep / 1000.0, dtype=latents_jax.dtype) + t_vec = put_data_on_devices(t_vec, data_sharding) - model_output = self._jitted_transformer_step( - params, latents_jax, img_ids_val, prompt_embeds_jax, txt_ids_val, vec_val, t_vec, guidance_vec_val - ) + with jax.named_scope(f"flux_transformer_step_{step_idx+1}"): + model_output = self._jitted_transformer_step( + params, latents_jax, img_ids_val, prompt_embeds_jax, txt_ids_val, vec_val, t_vec, guidance_vec_val + ) prev_sample, _ = self.scheduler.step( state=scheduler_state, @@ -318,11 +431,15 @@ def put_data_on_devices(x, sharding): sample=latents_jax, return_dict=False, ) - latents_jax = prev_sample + latents_jax = put_data_on_devices(prev_sample, active_latents_sharding) + latents_jax.block_until_ready() + t_step_duration = time.perf_counter() - t_step_start + max_logging.log( + f"{host_prefix} -> Step {step_idx+1}/{steps_to_run} complete in {t_step_duration:.4f}s | latents_sharding={getattr(latents_jax, 'sharding', None)}" + ) - latents_jax.block_until_ready() except Exception as e: - print(f"❌ {host_prefix} EXCEPTION IN DENOISE LOOP: {e}", flush=True) + max_logging.log(f"❌ {host_prefix} EXCEPTION IN DENOISE LOOP: {e}") import traceback traceback.print_exc() @@ -331,7 +448,7 @@ def put_data_on_devices(x, sharding): # Stage Sync 3: Phase B Complete multihost_utils.sync_global_devices("phase_b_complete") - print(f"{host_prefix} Passed Phase B Sync Barrier (phase_b_complete) successfully! ✅", flush=True) + max_logging.log(f"{host_prefix} Passed Phase B Sync Barrier (phase_b_complete) successfully! ✅") trace["denoise_loop"] = time.perf_counter() - t0 max_logging.log(f" -> [TIMING] Denoising Loop (Flux): {trace['denoise_loop']:.4f} seconds ⏱️") @@ -342,17 +459,14 @@ def put_data_on_devices(x, sharding): max_logging.log("[PHASE C] Decoding final latents to RGB image using JAX VAE decoder on TPU...") t0 = time.perf_counter() - # Apply Channel-wise Batch Normalization Scaling in packed sequence format (denormalize) - vae_bn_mean_seq = vae_bn_mean.reshape(1, 1, 128) - vae_bn_std_seq = vae_bn_std.reshape(1, 1, 128) - latents_bn = latents_jax * vae_bn_std_seq + vae_bn_mean_seq - - # Unpack packed latents back to spatial grid - latents_unpacked = unpack_latents(latents_bn, batch_size, 32, height, width) - - # Decode VAE latents to RGB pixels - decoded_out = self._jitted_vae_decode(vae_params, latents_unpacked) - # VAE output is in decoded_out.sample + # Decode VAE latents to RGB pixels using fused JIT vae_decode + data_sharding = self._get_dynamic_batch_sharding() + replicated_sharding = jax.sharding.NamedSharding(self.mesh, P()) + latents_jax = put_data_on_devices(latents_jax, data_sharding) + vae_bn_mean_jax = put_data_on_devices(jnp.array(vae_bn_mean, dtype=jnp.float32), replicated_sharding) + vae_bn_std_jax = put_data_on_devices(jnp.array(vae_bn_std, dtype=jnp.float32), replicated_sharding) + with jax.named_scope("vae_decoder"): + decoded_out = self._jitted_vae_decode(vae_params, latents_jax, vae_bn_mean_jax, vae_bn_std_jax, height, width) images_rgb = decoded_out.sample images_rgb.block_until_ready() diff --git a/src/maxdiffusion/tests/generate_flux2klein_smoke_test.py b/src/maxdiffusion/tests/generate_flux2klein_smoke_test.py index 24362d35d..0c7ba6639 100644 --- a/src/maxdiffusion/tests/generate_flux2klein_smoke_test.py +++ b/src/maxdiffusion/tests/generate_flux2klein_smoke_test.py @@ -17,6 +17,7 @@ import os import unittest import pytest +import jax import numpy as np from PIL import Image @@ -101,6 +102,7 @@ def test_flux2klein_9b_smoke(self): f"prompt={PROMPT}", "height=512", "width=512", + "per_device_batch_size=0.125" if jax.device_count() == 8 else "per_device_batch_size=0.25", "batch_size=1", "seed=42", "ici_fsdp_parallelism=-1", @@ -117,7 +119,7 @@ def test_flux2klein_9b_smoke(self): self.assertEqual(base_image.shape, test_image.shape) ssim_compare = ssim(base_image, test_image, channel_axis=-1, data_range=255) print(f"\n[SMOKE TEST 9B] SSIM Score: {ssim_compare:.6f}") - self.assertGreaterEqual(ssim_compare, 0.80) + self.assertGreaterEqual(ssim_compare, 0.8) if __name__ == "__main__": diff --git a/src/maxdiffusion/tests/images/ref_flux2klein_9b.png b/src/maxdiffusion/tests/images/ref_flux2klein_9b.png index 594464a8f..c27f959ac 100644 Binary files a/src/maxdiffusion/tests/images/ref_flux2klein_9b.png and b/src/maxdiffusion/tests/images/ref_flux2klein_9b.png differ