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..aae3add53 100644 --- a/src/maxdiffusion/generate_flux2klein.py +++ b/src/maxdiffusion/generate_flux2klein.py @@ -17,7 +17,6 @@ import gc import os import time -import sys from typing import List from absl import app @@ -25,6 +24,7 @@ import jax.numpy as jnp import numpy as np import flax +from flax import nnx from flax import linen as nn from flax.linen import partitioning as nn_partitioning from jax.sharding import Mesh @@ -35,7 +35,6 @@ from maxdiffusion.max_utils import create_device_mesh from maxdiffusion.train_utils import transformer_engine_context -from maxdiffusion.models.flux.transformers.transformer_flux_flax import Flux2KleinTransformer2DModel from maxdiffusion.models.vae_flax import FlaxAutoencoderKL from maxdiffusion.models.qwen3_flax import FlaxQwen3Config, FlaxQwen3Model from maxdiffusion.models.qwen3_utils import load_and_convert_qwen3_weights @@ -79,8 +78,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() @@ -132,17 +145,39 @@ def main(argv): # Import modules after jax.distributed.initialize() has run via pyconfig.initialize() from maxdiffusion.models.flux.util import ( - load_and_convert_flux_klein_weights, + load_and_convert_flux_klein_nnx_weights, load_and_convert_vae_weights, - cast_dict_to_bfloat16_inplace, ) from maxdiffusion.pipelines.flux.flux2klein_pipeline import FlaxFlux2KleinPipeline + from maxdiffusion.models.flux.transformers.transformer_flux_flax import ( + NNXFlux2KleinTransformer2DModel, + ) 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()) + assert calculated_batch_size >= 1, ( + f"Calculated global batch_size is {calculated_batch_size}, which is invalid (must be >= 1). " + f"per_device_batch_size={config.per_device_batch_size} multiplied by jax.device_count()={jax.device_count()} " + f"evaluated to {config.per_device_batch_size * jax.device_count()}, which truncates to 0. " + f"Please increase per_device_batch_size or specify an explicit batch_size in your configuration." + ) + 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." ) @@ -174,8 +209,7 @@ def main(argv): # 3. Resolve weights repository snapshots repo_id = getattr(config, "pretrained_model_name_or_path", None) if not repo_id: - depth_val = getattr(config, "depth", None) - repo_id = "black-forest-labs/FLUX.2-klein-9B" if depth_val == 24 else "black-forest-labs/FLUX.2-klein-4B" + raise ValueError("pretrained_model_name_or_path must be specified in configuration YAML or CLI.") max_logging.log(f"Target model detected: {repo_id}") if os.path.exists(repo_id): @@ -184,8 +218,13 @@ 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: + snapshot_dir = snapshot_download(repo_id=repo_id, revision=rev) max_logging.log(f"Host {jax.process_index()} using HF snapshot directory: {snapshot_dir}") safetensors_path = os.path.join(snapshot_dir, "transformer") @@ -195,8 +234,7 @@ 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) + pt_config = AutoConfig.from_pretrained(text_encoder_path) qwen3_config = FlaxQwen3Config( vocab_size=pt_config.vocab_size, @@ -217,9 +255,24 @@ 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 and repo_id: + try: + from huggingface_hub import hf_hub_download + + cfg_file = hf_hub_download(repo_id=repo_id, 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 from HF cache: {e}") num_double_layers = getattr(config, "num_double_layers", -1) if num_double_layers is None or num_double_layers <= 0: @@ -233,30 +286,30 @@ def main(argv): if num_attention_heads is None or num_attention_heads <= 0: num_attention_heads = transformer_pt_cfg.get("num_attention_heads", 24) - # 5. Instantiate JAX Flux2KleinTransformer2DModel - transformer = Flux2KleinTransformer2DModel( - in_channels=128, - num_layers=num_double_layers, - num_single_layers=depth, - attention_head_dim=128, - num_attention_heads=num_attention_heads, - joint_attention_dim=3 * pt_config.hidden_size, - pooled_projection_dim=768, - mlp_ratio=3.0, - qkv_bias=False, - joint_attention_bias=False, - x_embedder_bias=False, - proj_out_bias=False, - use_global_modulation=True, - use_swiglu=True, - axes_dims_rope=(32, 32, 32, 32), - theta=2000, - mesh=mesh, - dtype=jnp.bfloat16 if config.weights_dtype == "bfloat16" else jnp.float32, - weights_dtype=jnp.bfloat16 if config.weights_dtype == "bfloat16" else jnp.float32, - attention_kernel=config.attention, - scale_shift_order=getattr(config, "scale_shift_order", "shift_scale"), - ) + # 5. Instantiate JAX NNXFlux2KleinTransformer2DModel + def transformer_factory(rngs): + return NNXFlux2KleinTransformer2DModel( + rngs=rngs, + in_channels=128, + num_layers=num_double_layers, + num_single_layers=depth, + attention_head_dim=128, + num_attention_heads=num_attention_heads, + joint_attention_dim=3 * pt_config.hidden_size, + pooled_projection_dim=768, + mlp_ratio=3.0, + axes_dim=(32, 32, 32, 32), + theta=2000.0, + mesh=mesh, + dtype=jnp.bfloat16 if config.weights_dtype == "bfloat16" else jnp.float32, + weights_dtype=jnp.bfloat16 if config.weights_dtype == "bfloat16" else jnp.float32, + attention_kernel=config.attention, + scale_shift_order=getattr(config, "scale_shift_order", "shift_scale"), + ) + + abstract_transformer = nnx.eval_shape(transformer_factory, nnx.Rngs(jax.random.PRNGKey(0))) + graphdef, abstract_state, rest = nnx.split(abstract_transformer, nnx.Param, ...) + transformer = abstract_transformer # 6. Instantiate JAX VAE vae = FlaxAutoencoderKL( @@ -277,36 +330,13 @@ def main(argv): # 7. Evaluate shapes & extract mesh shardings max_logging.log("Evaluating model shapes and shardings...") - h_packed = config.height // 16 - w_packed = config.width // 16 - seq_len_img = h_packed * w_packed seq_len_txt = config.max_sequence_length - - img_dummy = jnp.zeros((config.batch_size, seq_len_img, 128)) - img_ids_dummy = jnp.zeros((config.batch_size, seq_len_img, 4)) - txt_dummy = jnp.zeros((config.batch_size, seq_len_txt, 3 * pt_config.hidden_size)) - txt_ids_dummy = jnp.zeros((config.batch_size, seq_len_txt, 4)) - vec_dummy = jnp.zeros((config.batch_size, 768)) - t_vec_dummy = jnp.zeros((config.batch_size,)) - guidance_vec_dummy = jnp.zeros((config.batch_size,)) dummy_img = jnp.zeros((config.batch_size, 3, 512, 512)) dummy_ids = jnp.zeros((config.batch_size, seq_len_txt), dtype=jnp.int32) dummy_mask = jnp.zeros((config.batch_size, seq_len_txt), dtype=jnp.int32) key = jax.random.PRNGKey(0) - key, vae_key, qwen_key = jax.random.split(key, 3) - - def transformer_init_fn(): - return transformer.init( - key, - hidden_states=img_dummy, - img_ids=img_ids_dummy, - encoder_hidden_states=txt_dummy, - txt_ids=txt_ids_dummy, - pooled_projections=vec_dummy, - timestep=t_vec_dummy, - guidance=guidance_vec_dummy, - ) + vae_key, qwen_key = jax.random.split(key, 2) def vae_init_fn(): return vae.init(vae_key, dummy_img) @@ -315,11 +345,10 @@ def qwen3_init_fn(): return qwen3_model.init(qwen_key, dummy_ids, dummy_mask) with mesh, nn_partitioning.axis_rules(config.logical_axis_rules): - abstract_transformer_vars = jax.eval_shape(transformer_init_fn) + logical_transformer_specs = nnx.get_partition_spec(abstract_state) abstract_vae_vars = jax.eval_shape(vae_init_fn) abstract_qwen3_vars = jax.eval_shape(qwen3_init_fn) - logical_transformer_specs = nn.get_partition_spec(abstract_transformer_vars) logical_vae_specs = nn.get_partition_spec(abstract_vae_vars) logical_qwen3_specs = nn.get_partition_spec(abstract_qwen3_vars) @@ -327,9 +356,9 @@ def qwen3_init_fn(): vae_mesh_shardings = nn.logical_to_mesh_sharding(logical_vae_specs, mesh, config.logical_axis_rules) qwen3_mesh_shardings = nn.logical_to_mesh_sharding(logical_qwen3_specs, mesh, config.logical_axis_rules) - transformer_shardings = flax.core.freeze(transformer_mesh_shardings["params"]) vae_shardings = flax.core.freeze(vae_mesh_shardings["params"]) qwen3_shardings = flax.core.freeze(qwen3_mesh_shardings["params"]) + transformer_shardings = transformer_mesh_shardings # 8. Load weights on Host CPU max_logging.log("Loading parameters on Host CPU...") @@ -342,11 +371,7 @@ def qwen3_init_fn(): def unbox_fn(x): return x.unbox() if isinstance(x, flax_spmd.LogicallyPartitioned) else x - params = jax.tree_util.tree_map( - unbox_fn, abstract_transformer_vars["params"], is_leaf=lambda k: isinstance(k, flax_spmd.LogicallyPartitioned) - ) - params = flax.core.unfreeze(params) - + t_sub0 = time.time() vae_params = jax.tree_util.tree_map( unbox_fn, abstract_vae_vars["params"], is_leaf=lambda k: isinstance(k, flax_spmd.LogicallyPartitioned) ) @@ -357,49 +382,43 @@ 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() - 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) + weight_dtype = jnp.bfloat16 if config.weights_dtype == "bfloat16" else jnp.float32 + + params = load_and_convert_flux_klein_nnx_weights( + safetensors_path, abstract_state, 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) qwen3_params = flax.core.freeze(qwen3_params) 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: - params = jax.tree_util.tree_map(max_utils.device_put_replicated, params, transformer_shardings) - except Exception as err: - max_logging.log("\n❌ jax.device_put(params, transformer_shardings) FAILED!") - flat_p = flax.traverse_util.flatten_dict(params) - flat_s = flax.traverse_util.flatten_dict(transformer_shardings) - k_p = set(flat_p.keys()) - k_s = set(flat_s.keys()) - max_logging.log(f"Keys in sharding spec but missing in params: {k_s - k_p}") - max_logging.log(f"Keys in params but missing in sharding spec: {k_p - k_s}") - sys.stdout.flush() - raise err + params = jax.tree_util.tree_map(max_utils.device_put_replicated, params, transformer_shardings) max_logging.log("Putting vae_params on TPU HBM...") 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 +445,19 @@ def unbox_fn(x): mesh=mesh, ) - active_prompts = partition_prompts(config.prompt, config.batch_size) + prompt_str = getattr(config, "prompt", None) + if not prompt_str: + raise ValueError("Prompt must be specified in the configuration YAML or passed via CLI prompt='...'") + 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 +503,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 +536,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/max_utils.py b/src/maxdiffusion/max_utils.py index 37027c27d..beb898d31 100644 --- a/src/maxdiffusion/max_utils.py +++ b/src/maxdiffusion/max_utils.py @@ -383,7 +383,13 @@ def device_put_replicated(x, sharding): Although the name indicates replication, this function can be used to also shard an array based on sharding. """ - return jax.make_array_from_callback(x.shape, sharding, lambda index: x[index]) + arr = getattr(x, "value", x) + shd = getattr(sharding, "value", sharding) + res = jax.make_array_from_callback(arr.shape, shd, lambda index: arr[index]) + if hasattr(x, "set_value"): + x.set_value(res) + return x + return res def fill_unspecified_mesh_axes(parallelism_vals, target_product, parallelism_type): diff --git a/src/maxdiffusion/models/flux/transformers/transformer_flux_flax.py b/src/maxdiffusion/models/flux/transformers/transformer_flux_flax.py index af8e3763a..9232670f0 100644 --- a/src/maxdiffusion/models/flux/transformers/transformer_flux_flax.py +++ b/src/maxdiffusion/models/flux/transformers/transformer_flux_flax.py @@ -14,7 +14,7 @@ limitations under the License. """ -from typing import Dict, Optional, Tuple +from typing import Dict, Optional, Tuple, Union import jax import math import jax.numpy as jnp @@ -27,11 +27,9 @@ AdaLayerNormZeroSingle, AdaLayerNormContinuous, AdaLayerNormZero, - NNXAdaLayerNormZeroSingle, NNXAdaLayerNormContinuous, - NNXAdaLayerNormZero, ) -from ...attention_flax import FlaxFluxAttention as FluxAttention, FlaxFluxAttention, apply_rope +from ...attention_flax import FlaxFluxAttention as FluxAttention, FlaxFluxAttention, apply_rope, NNXAttentionOp from flax import nnx from ...embeddings_flax import ( FluxPosEmbed, @@ -1278,64 +1276,115 @@ def __call__( return Transformer2DModelOutput(sample=output) -# ============================================================================= -# FLAX NNX MODEL IMPLEMENTATIONS FOR FLUX.2-KLEIN -# ============================================================================= +class NNXFlaxSwiGluFeedForward(nnx.Module): + """Flax NNX SwiGLU FeedForward module.""" + + def __init__( + self, + rngs: nnx.Rngs, + dim: int, + dim_out: int, + mult: float = 3.0, + dtype: jnp.dtype = jnp.float32, + weights_dtype: jnp.dtype = jnp.float32, + ): + inner_dim = int(dim * mult) + self.linear_in = nnx.Linear( + in_features=dim, + out_features=inner_dim * 2, + use_bias=False, + kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), ("embed", "mlp")), + dtype=dtype, + param_dtype=weights_dtype, + rngs=rngs, + ) + self.linear_out = nnx.Linear( + in_features=inner_dim, + out_features=dim_out, + use_bias=False, + kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), ("mlp", "embed")), + dtype=dtype, + param_dtype=weights_dtype, + rngs=rngs, + ) + + def __call__(self, x: jax.Array) -> jax.Array: + x = self.linear_in(x) + x1, x2 = jnp.split(x, 2, axis=-1) + hidden = nnx.silu(x1) * x2 + return self.linear_out(hidden) -class NNXFluxDoubleAttention(nnx.Module): +class NNXFluxAttention(nnx.Module): + """Flax NNX Double-Stream Joint Attention for FLUX.2-Klein.""" def __init__( self, rngs: nnx.Rngs, query_dim: int, - heads: int, - dim_head: int, - qkv_bias: bool = False, + heads: int = 8, + dim_head: int = 64, + attention_kernel: str = "dot_product", + flash_min_seq_length: int = 512, + flash_block_sizes: Optional[Dict[str, int]] = None, + mesh: Optional[jax.sharding.Mesh] = None, dtype: jnp.dtype = jnp.float32, weights_dtype: jnp.dtype = jnp.float32, + qkv_bias: bool = False, ): - self.query_dim = query_dim self.heads = heads self.dim_head = dim_head - inner_dim = heads * dim_head + inner_dim = dim_head * heads + scale = dim_head**-0.5 + + self.attention_op = NNXAttentionOp( + mesh=mesh, + attention_kernel=attention_kernel, + scale=scale, + heads=heads, + dim_head=dim_head, + flash_min_seq_length=flash_min_seq_length, + flash_block_sizes=flash_block_sizes, + dtype=dtype, + ) + + kernel_axes = ("embed", "heads") + proj_attn_kernel_axes = ("heads", "embed") - self.qkv = nnx.Linear( + self.i_qkv = nnx.Linear( in_features=query_dim, out_features=inner_dim * 3, use_bias=qkv_bias, - kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), ("embed", "heads")), + kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), kernel_axes), bias_init=nnx.with_partitioning(nnx.initializers.zeros, ("heads",)), dtype=dtype, param_dtype=weights_dtype, rngs=rngs, ) - self.encoder_qkv = nnx.Linear( + self.e_qkv = nnx.Linear( in_features=query_dim, out_features=inner_dim * 3, use_bias=qkv_bias, - kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), ("embed", "heads")), + kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), kernel_axes), bias_init=nnx.with_partitioning(nnx.initializers.zeros, ("heads",)), dtype=dtype, param_dtype=weights_dtype, rngs=rngs, ) - self.proj_attn = nnx.Linear( + self.i_proj = nnx.Linear( in_features=inner_dim, out_features=query_dim, - use_bias=True, - kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), ("heads", "embed")), - bias_init=nnx.with_partitioning(nnx.initializers.zeros, ("embed",)), + use_bias=False, + kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), proj_attn_kernel_axes), dtype=dtype, param_dtype=weights_dtype, rngs=rngs, ) - self.encoder_proj_attn = nnx.Linear( + self.e_proj = nnx.Linear( in_features=inner_dim, out_features=query_dim, - use_bias=True, - kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), ("heads", "embed")), - bias_init=nnx.with_partitioning(nnx.initializers.zeros, ("embed",)), + use_bias=False, + kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), proj_attn_kernel_axes), dtype=dtype, param_dtype=weights_dtype, rngs=rngs, @@ -1356,59 +1405,79 @@ def __init__( param_dtype=weights_dtype, rngs=rngs, ) + self.encoder_query_norm = nnx.RMSNorm( + num_features=dim_head, + epsilon=1e-6, + scale_init=nnx.with_partitioning(nnx.initializers.ones, ("heads",)), + dtype=dtype, + param_dtype=weights_dtype, + rngs=rngs, + ) + self.encoder_key_norm = nnx.RMSNorm( + num_features=dim_head, + epsilon=1e-6, + scale_init=nnx.with_partitioning(nnx.initializers.ones, ("heads",)), + dtype=dtype, + param_dtype=weights_dtype, + rngs=rngs, + ) def __call__( self, hidden_states: jax.Array, - encoder_hidden_states: jax.Array, - image_rotary_emb: Tuple[jax.Array, jax.Array], - ) -> Tuple[jax.Array, jax.Array]: - batch_size, img_len, _ = hidden_states.shape - txt_len = encoder_hidden_states.shape[1] - - qkv_img = self.qkv(hidden_states) - qkv_txt = self.encoder_qkv(encoder_hidden_states) - - q_img, k_img, v_img = jnp.split(qkv_img, 3, axis=-1) - q_txt, k_txt, v_txt = jnp.split(qkv_txt, 3, axis=-1) - - q_img = rearrange(q_img, "b l (h d) -> b l h d", h=self.heads) - k_img = rearrange(k_img, "b l (h d) -> b l h d", h=self.heads) - v_img = rearrange(v_img, "b l (h d) -> b l h d", h=self.heads) + encoder_hidden_states: Optional[jax.Array] = None, + image_rotary_emb: Optional[Tuple[jax.Array, jax.Array]] = None, + ) -> Tuple[jax.Array, Optional[jax.Array]]: + B, L = hidden_states.shape[:2] + H, D = self.heads, self.dim_head - q_txt = rearrange(q_txt, "b l (h d) -> b l h d", h=self.heads) - k_txt = rearrange(k_txt, "b l (h d) -> b l h d", h=self.heads) - v_txt = rearrange(v_txt, "b l (h d) -> b l h d", h=self.heads) + qkv_proj = self.i_qkv(hidden_states).reshape(B, L, 3, H, D) + query_proj, key_proj, value_proj = jnp.split(qkv_proj, 3, axis=2) + query_proj = self.query_norm(query_proj.squeeze(2)) + key_proj = self.key_norm(key_proj.squeeze(2)) + value_proj = value_proj.squeeze(2) - q_img = self.query_norm(q_img) - k_img = self.key_norm(k_img) - q_txt = self.query_norm(q_txt) - k_txt = self.key_norm(k_txt) + if encoder_hidden_states is not None: + B_enc, L_txt = encoder_hidden_states.shape[:2] + encoder_qkv_proj = self.e_qkv(encoder_hidden_states).reshape(B_enc, L_txt, 3, H, D) + enc_query_proj, enc_key_proj, enc_value_proj = jnp.split(encoder_qkv_proj, 3, axis=2) + enc_query_proj = self.encoder_query_norm(enc_query_proj.squeeze(2)) + enc_key_proj = self.encoder_key_norm(enc_key_proj.squeeze(2)) + enc_value_proj = enc_value_proj.squeeze(2) - q = jnp.concatenate([q_txt, q_img], axis=1) - k = jnp.concatenate([k_txt, k_img], axis=1) - v = jnp.concatenate([v_txt, v_img], axis=1) + query_proj = jnp.concatenate((enc_query_proj, query_proj), axis=1) + key_proj = jnp.concatenate((enc_key_proj, key_proj), axis=1) + value_proj = jnp.concatenate((enc_value_proj, value_proj), axis=1) if image_rotary_emb is not None: - q, k = apply_rope(q, k, image_rotary_emb) - - scale = self.dim_head**-0.5 - attn_weights = jnp.einsum("b q h d, b k h d -> b h q k", q, k, precision=None) * scale - attn_weights = jax.nn.softmax(attn_weights, axis=-1) - out = jnp.einsum("b h q k, b k h d -> b q h d", attn_weights, v, precision=None) + if not isinstance(image_rotary_emb, (tuple, list)): + image_rotary_emb_reordered = rearrange(image_rotary_emb, "n d (i j) -> n d i j", i=2, j=2) + else: + image_rotary_emb_reordered = image_rotary_emb + query_proj = query_proj.swapaxes(1, 2) + key_proj = key_proj.swapaxes(1, 2) + query_proj, key_proj = apply_rope(query_proj, key_proj, image_rotary_emb_reordered) + query_proj = query_proj.swapaxes(1, 2) + key_proj = key_proj.swapaxes(1, 2) - out = rearrange(out, "b l h d -> b l (h d)") + query_proj = query_proj.reshape(B, -1, H * D) + key_proj = key_proj.reshape(B, -1, H * D) + value_proj = value_proj.reshape(B, -1, H * D) - out_txt = out[:, :txt_len, :] - out_img = out[:, txt_len:, :] + attn_output = self.attention_op.apply_attention(query_proj, key_proj, value_proj) + context_attn_output = None - out_img = self.proj_attn(out_img) - out_txt = self.encoder_proj_attn(out_txt) + if encoder_hidden_states is not None: + context_attn_output = attn_output[:, : encoder_hidden_states.shape[1]] + attn_output = attn_output[:, encoder_hidden_states.shape[1] :] + attn_output = self.i_proj(attn_output) + context_attn_output = self.e_proj(context_attn_output) - return out_img, out_txt + return attn_output, context_attn_output class NNXFluxSingleAttention(nnx.Module): + """Flax NNX Single-Stream Attention for FLUX.2-Klein.""" def __init__( self, @@ -1416,33 +1485,28 @@ def __init__( dim: int, num_attention_heads: int, attention_head_dim: int, + attention_kernel: str = "dot_product", + flash_min_seq_length: int = 512, + flash_block_sizes: Optional[Dict[str, int]] = None, + mesh: Optional[jax.sharding.Mesh] = None, dtype: jnp.dtype = jnp.float32, weights_dtype: jnp.dtype = jnp.float32, ): - self.dim = dim - self.heads = num_attention_heads - self.dim_head = attention_head_dim - inner_dim = num_attention_heads * attention_head_dim + self.num_attention_heads = num_attention_heads + self.attention_head_dim = attention_head_dim + scale = attention_head_dim**-0.5 - self.to_qkv_mlp_proj = nnx.Linear( - in_features=dim, - out_features=inner_dim * 3 + int(dim * 4.0), - use_bias=False, - kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), ("embed", "mlp")), - dtype=dtype, - param_dtype=weights_dtype, - rngs=rngs, - ) - self.to_out = nnx.Linear( - in_features=inner_dim + int(dim * 4.0), - out_features=dim, - use_bias=False, - kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), ("mlp", "embed")), + self.attention_op = NNXAttentionOp( + mesh=mesh, + attention_kernel=attention_kernel, + scale=scale, + heads=num_attention_heads, + dim_head=attention_head_dim, + flash_min_seq_length=flash_min_seq_length, + flash_block_sizes=flash_block_sizes, dtype=dtype, - param_dtype=weights_dtype, - rngs=rngs, ) - self.norm_q = nnx.RMSNorm( + self.query_norm = nnx.RMSNorm( num_features=attention_head_dim, epsilon=1e-6, scale_init=nnx.with_partitioning(nnx.initializers.ones, ("heads",)), @@ -1450,7 +1514,7 @@ def __init__( param_dtype=weights_dtype, rngs=rngs, ) - self.norm_k = nnx.RMSNorm( + self.key_norm = nnx.RMSNorm( num_features=attention_head_dim, epsilon=1e-6, scale_init=nnx.with_partitioning(nnx.initializers.ones, ("heads",)), @@ -1459,42 +1523,9 @@ def __init__( rngs=rngs, ) - def __call__( - self, - hidden_states: jax.Array, - image_rotary_emb: Tuple[jax.Array, jax.Array], - ) -> jax.Array: - batch_size, seq_len, _ = hidden_states.shape - inner_dim = self.heads * self.dim_head - - qkv_mlp = self.to_qkv_mlp_proj(hidden_states) - qkv, mlp = jnp.split(qkv_mlp, [inner_dim * 3], axis=-1) - - q, k, v = jnp.split(qkv, 3, axis=-1) - q = rearrange(q, "b l (h d) -> b l h d", h=self.heads) - k = rearrange(k, "b l (h d) -> b l h d", h=self.heads) - v = rearrange(v, "b l (h d) -> b l h d", h=self.heads) - - q = self.norm_q(q) - k = self.norm_k(k) - - if image_rotary_emb is not None: - q, k = apply_rope(q, k, image_rotary_emb) - - scale = self.dim_head**-0.5 - attn_weights = jnp.einsum("b q h d, b k h d -> b h q k", q, k, precision=None) * scale - attn_weights = jax.nn.softmax(attn_weights, axis=-1) - attn_out = jnp.einsum("b h q k, b k h d -> b q h d", attn_weights, v, precision=None) - attn_out = rearrange(attn_out, "b l h d -> b l (h d)") - - mlp_act = jax.nn.gelu(mlp, approximate=True) - attn_mlp = jnp.concatenate([attn_out, mlp_act], axis=-1) - - out = self.to_out(attn_mlp) - return out - class NNXFluxDoubleTransformerBlock(nnx.Module): + """Flax NNX Double-Stream Transformer Block for FLUX.2-Klein.""" def __init__( self, @@ -1502,66 +1533,85 @@ def __init__( dim: int, num_attention_heads: int, attention_head_dim: int, - mlp_ratio: float = 4.0, + mlp_ratio: float = 3.0, + attention_kernel: str = "dot_product", + flash_min_seq_length: int = 512, + flash_block_sizes: Optional[Dict[str, int]] = None, + mesh: Optional[jax.sharding.Mesh] = None, dtype: jnp.dtype = jnp.float32, weights_dtype: jnp.dtype = jnp.float32, + qkv_bias: bool = False, ): self.dim = dim self.num_heads = num_attention_heads self.head_dim = attention_head_dim - mlp_hidden_dim = int(dim * mlp_ratio) - - self.img_norm1 = NNXAdaLayerNormZero(dim, dtype=dtype, weights_dtype=weights_dtype) - self.txt_norm1 = NNXAdaLayerNormZero(dim, dtype=dtype, weights_dtype=weights_dtype) - self.attn = NNXFluxDoubleAttention( - rngs=rngs, - query_dim=dim, - heads=num_attention_heads, - dim_head=attention_head_dim, + self.norm1 = nnx.LayerNorm( + num_features=dim, + use_bias=False, + use_scale=False, + epsilon=1e-6, dtype=dtype, - weights_dtype=weights_dtype, + param_dtype=weights_dtype, + rngs=rngs, ) - - self.img_mlp = nnx.Linear( - in_features=dim, - out_features=mlp_hidden_dim, - use_bias=True, - kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), ("embed", "mlp")), - bias_init=nnx.with_partitioning(nnx.initializers.zeros, (None,)), + self.norm1_context = nnx.LayerNorm( + num_features=dim, + use_bias=False, + use_scale=False, + epsilon=1e-6, dtype=dtype, param_dtype=weights_dtype, rngs=rngs, ) - self.img_mlp_out = nnx.Linear( - in_features=mlp_hidden_dim, - out_features=dim, - use_bias=True, - kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), ("mlp", "embed")), - bias_init=nnx.with_partitioning(nnx.initializers.zeros, (None,)), + self.norm2 = nnx.LayerNorm( + num_features=dim, + use_bias=False, + use_scale=False, + epsilon=1e-6, dtype=dtype, param_dtype=weights_dtype, rngs=rngs, ) - self.txt_mlp = nnx.Linear( - in_features=dim, - out_features=mlp_hidden_dim, - use_bias=True, - kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), ("embed", "mlp")), - bias_init=nnx.with_partitioning(nnx.initializers.zeros, (None,)), + self.norm2_context = nnx.LayerNorm( + num_features=dim, + use_bias=False, + use_scale=False, + epsilon=1e-6, dtype=dtype, param_dtype=weights_dtype, rngs=rngs, ) - self.txt_mlp_out = nnx.Linear( - in_features=mlp_hidden_dim, - out_features=dim, - use_bias=True, - kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), ("mlp", "embed")), - bias_init=nnx.with_partitioning(nnx.initializers.zeros, (None,)), + + self.attn = NNXFluxAttention( + rngs=rngs, + query_dim=dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + attention_kernel=attention_kernel, + flash_min_seq_length=flash_min_seq_length, + flash_block_sizes=flash_block_sizes, + mesh=mesh, dtype=dtype, - param_dtype=weights_dtype, + weights_dtype=weights_dtype, + qkv_bias=qkv_bias, + ) + + self.ff = NNXFlaxSwiGluFeedForward( + rngs=rngs, + dim=dim, + dim_out=dim, + mult=mlp_ratio, + dtype=dtype, + weights_dtype=weights_dtype, + ) + self.ff_context = NNXFlaxSwiGluFeedForward( rngs=rngs, + dim=dim, + dim_out=dim, + mult=mlp_ratio, + dtype=dtype, + weights_dtype=weights_dtype, ) def __call__( @@ -1573,33 +1623,49 @@ def __call__( temb_mod_img: Optional[jax.Array] = None, temb_mod_txt: Optional[jax.Array] = None, ) -> Tuple[jax.Array, jax.Array]: - norm_h, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.img_norm1(hidden_states, emb=temb_mod_img) - norm_enc, c_gate_msa_txt, c_shift_mlp_txt, c_scale_mlp_txt, c_gate_mlp_txt = self.txt_norm1( - encoder_hidden_states, emb=temb_mod_txt - ) + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = jnp.split(temb_mod_img, 6, axis=-1) + c_shift_msa, c_scale_msa, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = jnp.split(temb_mod_txt, 6, axis=-1) + + shift_msa = jnp.expand_dims(shift_msa, axis=1) + scale_msa = jnp.expand_dims(scale_msa, axis=1) + gate_msa = jnp.expand_dims(gate_msa, axis=1) + shift_mlp = jnp.expand_dims(shift_mlp, axis=1) + scale_mlp = jnp.expand_dims(scale_mlp, axis=1) + gate_mlp = jnp.expand_dims(gate_mlp, axis=1) + + c_shift_msa = jnp.expand_dims(c_shift_msa, axis=1) + c_scale_msa = jnp.expand_dims(c_scale_msa, axis=1) + c_gate_msa = jnp.expand_dims(c_gate_msa, axis=1) + c_shift_mlp = jnp.expand_dims(c_shift_mlp, axis=1) + c_scale_mlp = jnp.expand_dims(c_scale_mlp, axis=1) + c_gate_mlp = jnp.expand_dims(c_gate_mlp, axis=1) + + norm1_h = self.norm1(hidden_states) * (1.0 + scale_msa) + shift_msa + norm1_enc = self.norm1_context(encoder_hidden_states) * (1.0 + c_scale_msa) + c_shift_msa attn_img, attn_txt = self.attn( - hidden_states=norm_h, - encoder_hidden_states=norm_enc, + hidden_states=norm1_h, + encoder_hidden_states=norm1_enc, image_rotary_emb=image_rotary_emb, ) - hidden_states = hidden_states + c_gate_msa * attn_img - encoder_hidden_states = encoder_hidden_states + c_gate_msa_txt * attn_txt + hidden_states = hidden_states + gate_msa * attn_img + encoder_hidden_states = encoder_hidden_states + c_gate_msa * attn_txt - norm_h_mlp = norm_h * (1.0 + c_scale_mlp) + c_shift_mlp - norm_enc_mlp = norm_enc * (1.0 + c_scale_mlp_txt) + c_shift_mlp_txt + norm2_h = self.norm2(hidden_states) * (1.0 + scale_mlp) + shift_mlp + norm2_enc = self.norm2_context(encoder_hidden_states) * (1.0 + c_scale_mlp) + c_shift_mlp - img_ff = self.img_mlp_out(jax.nn.gelu(self.img_mlp(norm_h_mlp), approximate=True)) - txt_ff = self.txt_mlp_out(jax.nn.gelu(self.txt_mlp(norm_enc_mlp), approximate=True)) + mlp_output = self.ff(norm2_h) + encoder_mlp_output = self.ff_context(norm2_enc) - hidden_states = hidden_states + c_gate_mlp * img_ff - encoder_hidden_states = encoder_hidden_states + c_gate_mlp_txt * txt_ff + hidden_states = hidden_states + gate_mlp * mlp_output + encoder_hidden_states = encoder_hidden_states + c_gate_mlp * encoder_mlp_output return encoder_hidden_states, hidden_states class NNXFluxSingleTransformerBlock(nnx.Module): + """Flax NNX Single-Stream Transformer Block for FLUX.2-Klein.""" def __init__( self, @@ -1607,16 +1673,59 @@ def __init__( dim: int, num_attention_heads: int, attention_head_dim: int, + mlp_ratio: float = 3.0, + attention_kernel: str = "dot_product", + flash_min_seq_length: int = 512, + flash_block_sizes: Optional[Dict[str, int]] = None, + mesh: Optional[jax.sharding.Mesh] = None, dtype: jnp.dtype = jnp.float32, weights_dtype: jnp.dtype = jnp.float32, ): self.dim = dim - self.norm = NNXAdaLayerNormZeroSingle(dim, dtype=dtype, weights_dtype=weights_dtype) + self.num_attention_heads = num_attention_heads + self.attention_head_dim = attention_head_dim + mlp_hidden_dim = int(dim * mlp_ratio) + + self.norm = nnx.LayerNorm( + num_features=dim, + use_bias=False, + use_scale=False, + epsilon=1e-6, + dtype=dtype, + param_dtype=weights_dtype, + rngs=rngs, + ) + + out_dim = dim * 3 + 2 * mlp_hidden_dim + self.linear1 = nnx.Linear( + in_features=dim, + out_features=out_dim, + use_bias=False, + kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), ("embed", "mlp")), + bias_init=nnx.with_partitioning(nnx.initializers.zeros, (None,)), + dtype=dtype, + param_dtype=weights_dtype, + rngs=rngs, + ) + self.linear2 = nnx.Linear( + in_features=dim + mlp_hidden_dim, + out_features=dim, + use_bias=False, + kernel_init=nnx.with_partitioning(nnx.initializers.lecun_normal(), ("mlp", "embed")), + bias_init=nnx.with_partitioning(nnx.initializers.zeros, (None,)), + dtype=dtype, + param_dtype=weights_dtype, + rngs=rngs, + ) self.attn = NNXFluxSingleAttention( rngs=rngs, dim=dim, num_attention_heads=num_attention_heads, attention_head_dim=attention_head_dim, + attention_kernel=attention_kernel, + flash_min_seq_length=flash_min_seq_length, + flash_block_sizes=flash_block_sizes, + mesh=mesh, dtype=dtype, weights_dtype=weights_dtype, ) @@ -1628,22 +1737,55 @@ def __call__( image_rotary_emb: Tuple[jax.Array, jax.Array], temb_mod: Optional[jax.Array] = None, ) -> jax.Array: - norm_hidden_states, gate_msa = self.norm(hidden_states, emb=temb_mod) - attn_output = self.attn( - hidden_states=norm_hidden_states, - image_rotary_emb=image_rotary_emb, - ) - hidden_states = hidden_states + gate_msa * attn_output + residual = hidden_states + shift_msa, scale_msa, gate = jnp.split(temb_mod, 3, axis=-1) + shift_msa = jnp.expand_dims(shift_msa, axis=1) + scale_msa = jnp.expand_dims(scale_msa, axis=1) + gate = jnp.expand_dims(gate, axis=1) + + norm_hidden_states = self.norm(hidden_states) + norm_hidden_states = (1 + scale_msa) * norm_hidden_states + shift_msa + + qkv, mlp = jnp.split(self.linear1(norm_hidden_states), [3 * self.dim], axis=-1) + B, L = hidden_states.shape[:2] + H, D = self.num_attention_heads, qkv.shape[-1] // (self.num_attention_heads * 3) + qkv_proj = qkv.reshape(B, L, 3, H, D).transpose(2, 0, 3, 1, 4) + q, k, v = qkv_proj + + q = self.attn.query_norm(q) + k = self.attn.key_norm(k) + + if image_rotary_emb is not None: + if isinstance(image_rotary_emb, (tuple, list)): + image_rotary_emb_reordered = image_rotary_emb + else: + image_rotary_emb_reordered = rearrange(image_rotary_emb, "n d (i j) -> n d i j", i=2, j=2) + q, k = apply_rope(q, k, image_rotary_emb_reordered) + + q = q.transpose(0, 2, 1, 3).reshape(q.shape[0], q.shape[2], -1) + k = k.transpose(0, 2, 1, 3).reshape(k.shape[0], k.shape[2], -1) + v = v.transpose(0, 2, 1, 3).reshape(v.shape[0], v.shape[2], -1) + + attn_output = self.attn.attention_op.apply_attention(q, k, v) + + mlp1, mlp2 = jnp.split(mlp, 2, axis=-1) + mlp_activated = nnx.silu(mlp1) * mlp2 + + attn_mlp = jnp.concatenate([attn_output, mlp_activated], axis=2) + hidden_states = self.linear2(attn_mlp) + hidden_states = gate * hidden_states + hidden_states = residual + hidden_states return hidden_states -class NNXFluxTransformer2DModel(nnx.Module): +class NNXFlux2KleinTransformer2DModel(nnx.Module): + """Flax NNX Top-Level FLUX.2-Klein Transformer 2D Model.""" def __init__( self, rngs: nnx.Rngs, patch_size: int = 1, - in_channels: int = 64, + in_channels: int = 128, num_layers: int = 5, num_single_layers: int = 20, attention_head_dim: int = 128, @@ -1651,10 +1793,16 @@ def __init__( joint_attention_dim: int = 4096, pooled_projection_dim: int = 768, guidance_embeds: bool = True, - axes_dim: Tuple[int, ...] = (16, 56, 56), - theta: float = 10000.0, + axes_dim: Tuple[int, ...] = (32, 32, 32, 32), + theta: float = 2000.0, + mlp_ratio: float = 3.0, + attention_kernel: str = "dot_product", + flash_min_seq_length: int = 512, + flash_block_sizes: Optional[Dict[str, int]] = None, + mesh: Optional[jax.sharding.Mesh] = None, dtype: jnp.dtype = jnp.float32, weights_dtype: jnp.dtype = jnp.float32, + scale_shift_order: str = "scale_shift", ): self.in_channels = in_channels self.out_channels = in_channels @@ -1663,6 +1811,7 @@ def __init__( self.num_single_layers = num_single_layers self.attention_head_dim = attention_head_dim self.num_attention_heads = num_attention_heads + self.joint_attention_dim = joint_attention_dim self.inner_dim = num_attention_heads * attention_head_dim self.dtype = dtype @@ -1679,7 +1828,7 @@ def __init__( self.double_stream_modulation_img = nnx.Linear( in_features=self.inner_dim, out_features=6 * self.inner_dim, - bias_init=nnx.with_partitioning(nnx.initializers.zeros, (None,)), + use_bias=False, dtype=dtype, param_dtype=weights_dtype, rngs=rngs, @@ -1687,7 +1836,7 @@ def __init__( self.double_stream_modulation_txt = nnx.Linear( in_features=self.inner_dim, out_features=6 * self.inner_dim, - bias_init=nnx.with_partitioning(nnx.initializers.zeros, (None,)), + use_bias=False, dtype=dtype, param_dtype=weights_dtype, rngs=rngs, @@ -1695,7 +1844,7 @@ def __init__( self.single_stream_modulation = nnx.Linear( in_features=self.inner_dim, out_features=3 * self.inner_dim, - bias_init=nnx.with_partitioning(nnx.initializers.zeros, (None,)), + use_bias=False, dtype=dtype, param_dtype=weights_dtype, rngs=rngs, @@ -1704,6 +1853,7 @@ def __init__( self.x_embedder = nnx.Linear( in_features=in_channels, out_features=self.inner_dim, + use_bias=False, dtype=dtype, param_dtype=weights_dtype, rngs=rngs, @@ -1711,6 +1861,7 @@ def __init__( self.context_embedder = nnx.Linear( in_features=joint_attention_dim, out_features=self.inner_dim, + use_bias=False, dtype=dtype, param_dtype=weights_dtype, rngs=rngs, @@ -1723,6 +1874,11 @@ def __init__( dim=self.inner_dim, num_attention_heads=num_attention_heads, attention_head_dim=attention_head_dim, + mlp_ratio=mlp_ratio, + attention_kernel=attention_kernel, + flash_min_seq_length=flash_min_seq_length, + flash_block_sizes=flash_block_sizes, + mesh=mesh, dtype=dtype, weights_dtype=weights_dtype, ) @@ -1737,6 +1893,11 @@ def __init__( dim=self.inner_dim, num_attention_heads=num_attention_heads, attention_head_dim=attention_head_dim, + mlp_ratio=mlp_ratio, + attention_kernel=attention_kernel, + flash_min_seq_length=flash_min_seq_length, + flash_block_sizes=flash_block_sizes, + mesh=mesh, dtype=dtype, weights_dtype=weights_dtype, ) @@ -1748,13 +1909,14 @@ def __init__( rngs=rngs, embedding_dim=self.inner_dim, eps=1e-6, + scale_shift_order=scale_shift_order, dtype=dtype, weights_dtype=weights_dtype, ) self.proj_out = nnx.Linear( in_features=self.inner_dim, out_features=in_channels, - use_bias=True, + use_bias=False, dtype=dtype, param_dtype=weights_dtype, rngs=rngs, @@ -1764,12 +1926,13 @@ def __call__( self, hidden_states: jax.Array, encoder_hidden_states: jax.Array, - pooled_projections: jax.Array, - timestep: jax.Array, - img_ids: jax.Array, - txt_ids: jax.Array, + pooled_projections: Optional[jax.Array] = None, + timestep: Optional[jax.Array] = None, + img_ids: Optional[jax.Array] = None, + txt_ids: Optional[jax.Array] = None, guidance: Optional[jax.Array] = None, - ) -> jax.Array: + return_dict: bool = True, + ) -> Union[jax.Array, Transformer2DModelOutput]: hidden_states = self.x_embedder(hidden_states) timestep = timestep * 1000.0 if guidance is not None: @@ -1777,7 +1940,7 @@ def __call__( temb = self.time_text_embed(timestep, guidance, pooled_projections) temb = temb.astype(hidden_states.dtype) - temb_silu = jax.nn.silu(temb) + temb_silu = nnx.silu(temb) double_stream_mod_img = self.double_stream_modulation_img(temb_silu) double_stream_mod_txt = self.double_stream_modulation_txt(temb_silu) single_stream_mod = self.single_stream_modulation(temb_silu) @@ -1821,4 +1984,7 @@ def __call__( hidden_states = hidden_states[:, num_txt_tokens:, ...] hidden_states = self.norm_out(hidden_states, temb) output = self.proj_out(hidden_states) - return output + + if not return_dict: + return (output,) + return Transformer2DModelOutput(sample=output) diff --git a/src/maxdiffusion/models/flux/util.py b/src/maxdiffusion/models/flux/util.py index 952519776..8941ecb01 100644 --- a/src/maxdiffusion/models/flux/util.py +++ b/src/maxdiffusion/models/flux/util.py @@ -17,6 +17,7 @@ # copied from https://github.com/ml-gde/jflux/blob/main/jflux/util.py import os from dataclasses import dataclass +from typing import Any, Optional import jax from jax.typing import DTypeLike @@ -300,17 +301,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 +399,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 +412,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 +426,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 +568,381 @@ def convert_and_transpose_tensor(tensor, transpose=False): return params -def load_and_convert_vae_weights(safetensors_path, jax_params): +def load_and_convert_flux_klein_nnx_weights( + safetensors_path: str, + nnx_state: Any, + num_double_layers: int, + num_single_layers: int, + dtype=None, + pt_state_dict: Optional[dict] = None, +): + """Loads FLUX.2-Klein weights directly into an NNX State PyTree in target dtype.""" + import glob + import gc + from safetensors.numpy import load_file + import numpy as np + from flax import nnx + + if pt_state_dict is None: + max_logging.log(f"Loading transformer safetensors from: {safetensors_path}") + if os.path.isdir(safetensors_path): + st_files = sorted(glob.glob(os.path.join(safetensors_path, "*.safetensors"))) + else: + st_files = [safetensors_path] + pt_state_dict = {} + for st_file in st_files: + pt_state_dict.update(load_file(st_file)) + + flat_state = dict(nnx.to_flat_state(nnx_state)) + target_dtype = dtype if dtype is not None else jnp.bfloat16 + + def convert_and_transpose_tensor(tensor, transpose=False, is_norm=False): + if transpose and len(tensor.shape) == 2: + tensor = tensor.T + leaf_dtype = jnp.float32 if is_norm else target_dtype + return jnp.array(tensor, dtype=leaf_dtype) + + def set_val(var, tensor): + if hasattr(var, "set_value"): + var.set_value(tensor) + elif hasattr(var, "value"): + var.value = tensor + return var + + # Global layers + if ("context_embedder", "kernel") in flat_state: + set_val( + flat_state[("context_embedder", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop("context_embedder.weight"), transpose=True), + ) + if ("x_embedder", "kernel") in flat_state: + set_val( + flat_state[("x_embedder", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop("x_embedder.weight"), transpose=True), + ) + if ("double_stream_modulation_img", "kernel") in flat_state: + set_val( + flat_state[("double_stream_modulation_img", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop("double_stream_modulation_img.linear.weight"), transpose=True), + ) + if ("double_stream_modulation_txt", "kernel") in flat_state: + set_val( + flat_state[("double_stream_modulation_txt", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop("double_stream_modulation_txt.linear.weight"), transpose=True), + ) + if ("single_stream_modulation", "kernel") in flat_state: + set_val( + flat_state[("single_stream_modulation", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop("single_stream_modulation.linear.weight"), transpose=True), + ) + if ("proj_out", "kernel") in flat_state: + set_val( + flat_state[("proj_out", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop("proj_out.weight"), transpose=True), + ) + + # norm_out + if ("norm_out", "linear", "kernel") in flat_state: + set_val( + flat_state[("norm_out", "linear", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop("norm_out.linear.weight"), transpose=True), + ) + + # Timestep / Guidance / Text projections + if ( + "time_guidance_embed.timestep_embedder.linear_1.weight" in pt_state_dict + and ( + "time_text_embed", + "timestep_embedder", + "linear_1", + "kernel", + ) + in flat_state + ): + set_val( + flat_state[("time_text_embed", "timestep_embedder", "linear_1", "kernel")], + convert_and_transpose_tensor( + pt_state_dict.pop("time_guidance_embed.timestep_embedder.linear_1.weight"), transpose=True + ), + ) + if ( + "time_guidance_embed.timestep_embedder.linear_1.bias" in pt_state_dict + and ( + "time_text_embed", + "timestep_embedder", + "linear_1", + "bias", + ) + in flat_state + ): + set_val( + flat_state[("time_text_embed", "timestep_embedder", "linear_1", "bias")], + convert_and_transpose_tensor(pt_state_dict.pop("time_guidance_embed.timestep_embedder.linear_1.bias")), + ) + if ( + "time_guidance_embed.timestep_embedder.linear_2.weight" in pt_state_dict + and ( + "time_text_embed", + "timestep_embedder", + "linear_2", + "kernel", + ) + in flat_state + ): + set_val( + flat_state[("time_text_embed", "timestep_embedder", "linear_2", "kernel")], + convert_and_transpose_tensor( + pt_state_dict.pop("time_guidance_embed.timestep_embedder.linear_2.weight"), transpose=True + ), + ) + if ( + "time_guidance_embed.timestep_embedder.linear_2.bias" in pt_state_dict + and ( + "time_text_embed", + "timestep_embedder", + "linear_2", + "bias", + ) + in flat_state + ): + set_val( + flat_state[("time_text_embed", "timestep_embedder", "linear_2", "bias")], + convert_and_transpose_tensor(pt_state_dict.pop("time_guidance_embed.timestep_embedder.linear_2.bias")), + ) + + if ( + "time_guidance_embed.guidance_embedder.linear_1.weight" in pt_state_dict + and ( + "time_text_embed", + "guidance_embedder", + "linear_1", + "kernel", + ) + in flat_state + ): + set_val( + flat_state[("time_text_embed", "guidance_embedder", "linear_1", "kernel")], + convert_and_transpose_tensor( + pt_state_dict.pop("time_guidance_embed.guidance_embedder.linear_1.weight"), transpose=True + ), + ) + if ( + "time_guidance_embed.guidance_embedder.linear_1.bias" in pt_state_dict + and ( + "time_text_embed", + "guidance_embedder", + "linear_1", + "bias", + ) + in flat_state + ): + set_val( + flat_state[("time_text_embed", "guidance_embedder", "linear_1", "bias")], + convert_and_transpose_tensor(pt_state_dict.pop("time_guidance_embed.guidance_embedder.linear_1.bias")), + ) + if ( + "time_guidance_embed.guidance_embedder.linear_2.weight" in pt_state_dict + and ( + "time_text_embed", + "guidance_embedder", + "linear_2", + "kernel", + ) + in flat_state + ): + set_val( + flat_state[("time_text_embed", "guidance_embedder", "linear_2", "kernel")], + convert_and_transpose_tensor( + pt_state_dict.pop("time_guidance_embed.guidance_embedder.linear_2.weight"), transpose=True + ), + ) + if ( + "time_guidance_embed.guidance_embedder.linear_2.bias" in pt_state_dict + and ( + "time_text_embed", + "guidance_embedder", + "linear_2", + "bias", + ) + in flat_state + ): + set_val( + flat_state[("time_text_embed", "guidance_embedder", "linear_2", "bias")], + convert_and_transpose_tensor(pt_state_dict.pop("time_guidance_embed.guidance_embedder.linear_2.bias")), + ) + + if ( + "time_guidance_embed.text_embedder.linear_1.weight" in pt_state_dict + and ( + "time_text_embed", + "pooled_embedder", + "linear_1", + "kernel", + ) + in flat_state + ): + set_val( + flat_state[("time_text_embed", "pooled_embedder", "linear_1", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop("time_guidance_embed.text_embedder.linear_1.weight"), transpose=True), + ) + if ( + "time_guidance_embed.text_embedder.linear_1.bias" in pt_state_dict + and ( + "time_text_embed", + "pooled_embedder", + "linear_1", + "bias", + ) + in flat_state + ): + set_val( + flat_state[("time_text_embed", "pooled_embedder", "linear_1", "bias")], + convert_and_transpose_tensor(pt_state_dict.pop("time_guidance_embed.text_embedder.linear_1.bias")), + ) + if ( + "time_guidance_embed.text_embedder.linear_2.weight" in pt_state_dict + and ( + "time_text_embed", + "pooled_embedder", + "linear_2", + "kernel", + ) + in flat_state + ): + set_val( + flat_state[("time_text_embed", "pooled_embedder", "linear_2", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop("time_guidance_embed.text_embedder.linear_2.weight"), transpose=True), + ) + if ( + "time_guidance_embed.text_embedder.linear_2.bias" in pt_state_dict + and ( + "time_text_embed", + "pooled_embedder", + "linear_2", + "bias", + ) + in flat_state + ): + set_val( + flat_state[("time_text_embed", "pooled_embedder", "linear_2", "bias")], + convert_and_transpose_tensor(pt_state_dict.pop("time_guidance_embed.text_embedder.linear_2.bias")), + ) + + # Double blocks + for block_idx in range(num_double_layers): + prefix = f"transformer_blocks.{block_idx}." + to_q = pt_state_dict.pop(prefix + "attn.to_q.weight").T + to_k = pt_state_dict.pop(prefix + "attn.to_k.weight").T + to_v = pt_state_dict.pop(prefix + "attn.to_v.weight").T + set_val( + flat_state[("double_blocks", block_idx, "attn", "i_qkv", "kernel")], + jnp.array(np.concatenate([to_q, to_k, to_v], axis=1), dtype=target_dtype), + ) + + add_q = pt_state_dict.pop(prefix + "attn.add_q_proj.weight").T + add_k = pt_state_dict.pop(prefix + "attn.add_k_proj.weight").T + add_v = pt_state_dict.pop(prefix + "attn.add_v_proj.weight").T + set_val( + flat_state[("double_blocks", block_idx, "attn", "e_qkv", "kernel")], + jnp.array(np.concatenate([add_q, add_k, add_v], axis=1), dtype=target_dtype), + ) + + set_val( + flat_state[("double_blocks", block_idx, "attn", "i_proj", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop(prefix + "attn.to_out.0.weight"), transpose=True), + ) + set_val( + flat_state[("double_blocks", block_idx, "attn", "e_proj", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop(prefix + "attn.to_add_out.weight"), transpose=True), + ) + + set_val( + flat_state[("double_blocks", block_idx, "attn", "query_norm", "scale")], + convert_and_transpose_tensor(pt_state_dict.pop(prefix + "attn.norm_q.weight"), is_norm=True), + ) + set_val( + flat_state[("double_blocks", block_idx, "attn", "key_norm", "scale")], + convert_and_transpose_tensor(pt_state_dict.pop(prefix + "attn.norm_k.weight"), is_norm=True), + ) + set_val( + flat_state[("double_blocks", block_idx, "attn", "encoder_query_norm", "scale")], + convert_and_transpose_tensor(pt_state_dict.pop(prefix + "attn.norm_added_q.weight"), is_norm=True), + ) + set_val( + flat_state[("double_blocks", block_idx, "attn", "encoder_key_norm", "scale")], + convert_and_transpose_tensor(pt_state_dict.pop(prefix + "attn.norm_added_k.weight"), is_norm=True), + ) + + set_val( + flat_state[("double_blocks", block_idx, "ff", "linear_in", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop(prefix + "ff.linear_in.weight"), transpose=True), + ) + set_val( + flat_state[("double_blocks", block_idx, "ff", "linear_out", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop(prefix + "ff.linear_out.weight"), transpose=True), + ) + set_val( + flat_state[("double_blocks", block_idx, "ff_context", "linear_in", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop(prefix + "ff_context.linear_in.weight"), transpose=True), + ) + set_val( + flat_state[("double_blocks", block_idx, "ff_context", "linear_out", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop(prefix + "ff_context.linear_out.weight"), transpose=True), + ) + + # Single blocks + for block_idx in range(num_single_layers): + s_prefix = f"single_transformer_blocks.{block_idx}." + set_val( + flat_state[("single_blocks", block_idx, "linear1", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop(s_prefix + "attn.to_qkv_mlp_proj.weight"), transpose=True), + ) + set_val( + flat_state[("single_blocks", block_idx, "linear2", "kernel")], + convert_and_transpose_tensor(pt_state_dict.pop(s_prefix + "attn.to_out.weight"), transpose=True), + ) + set_val( + flat_state[("single_blocks", block_idx, "attn", "query_norm", "scale")], + convert_and_transpose_tensor(pt_state_dict.pop(s_prefix + "attn.norm_q.weight"), is_norm=True), + ) + set_val( + flat_state[("single_blocks", block_idx, "attn", "key_norm", "scale")], + convert_and_transpose_tensor(pt_state_dict.pop(s_prefix + "attn.norm_k.weight"), is_norm=True), + ) + + for path, var in flat_state.items(): + val = var.get_value() if hasattr(var, "get_value") else getattr(var, "value", var) + if isinstance(val, jax.ShapeDtypeStruct): + set_val(var, jnp.zeros(val.shape, dtype=val.dtype)) + + del pt_state_dict + gc.collect() + max_logging.log("NNX Weight conversion complete & verified!") + return nnx.from_flat_state(flat_state) + + +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/normalization_flax.py b/src/maxdiffusion/models/normalization_flax.py index abe63f1db..2ef02a578 100644 --- a/src/maxdiffusion/models/normalization_flax.py +++ b/src/maxdiffusion/models/normalization_flax.py @@ -187,11 +187,13 @@ def __init__( rngs: nnx.Rngs, embedding_dim: int, eps: float = 1e-6, + scale_shift_order: str = "shift_scale", dtype: jnp.dtype = jnp.float32, weights_dtype: jnp.dtype = jnp.float32, ): self.embedding_dim = embedding_dim self.eps = eps + self.scale_shift_order = scale_shift_order self.dtype = dtype self.layer_norm = nnx.LayerNorm( num_features=embedding_dim, epsilon=eps, use_bias=False, use_scale=False, dtype=dtype, rngs=rngs @@ -199,7 +201,7 @@ def __init__( self.linear = nnx.Linear( in_features=embedding_dim, out_features=embedding_dim * 2, - use_bias=True, + use_bias=False, dtype=dtype, param_dtype=weights_dtype, rngs=rngs, @@ -207,7 +209,10 @@ def __init__( def __call__(self, x: jax.Array, conditioning_embedding: jax.Array) -> jax.Array: emb = self.linear(jax.nn.silu(conditioning_embedding)) - scale, shift = jnp.split(emb, 2, axis=-1) + if self.scale_shift_order == "shift_scale": + shift, scale = jnp.split(emb, 2, axis=-1) + else: + scale, shift = jnp.split(emb, 2, axis=-1) x_norm = self.layer_norm(x) return (1.0 + scale[:, None, :]) * x_norm + shift[:, None, :] 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..2b30b2c7e 100644 --- a/src/maxdiffusion/pipelines/flux/flux2klein_pipeline.py +++ b/src/maxdiffusion/pipelines/flux/flux2klein_pipeline.py @@ -30,14 +30,18 @@ from maxdiffusion import max_logging 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 flax import nnx +from ...models.flux.transformers.transformer_flux_flax import ( + Flux2KleinTransformer2DModel, + NNXFlux2KleinTransformer2DModel, + Transformer2DModelOutput, +) +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, ) @@ -51,7 +55,7 @@ class FlaxFlux2KleinPipeline(FlaxDiffusionPipeline): def __init__( self, - transformer: Flux2KleinTransformer2DModel, + transformer: Union[Flux2KleinTransformer2DModel, NNXFlux2KleinTransformer2DModel], vae: FlaxAutoencoderKL, text_encoder: FlaxQwen3Model, tokenizer, @@ -70,6 +74,7 @@ def __init__( ) self._config = config self.mesh = mesh + self.tokenizer = tokenizer # JIT compilation cache self._jitted_qwen3_forward = None @@ -84,27 +89,146 @@ def _setup_jit_functions(self): def qwen3_forward(q_params, ids, mask): return self.text_encoder.apply({"params": q_params}, input_ids=ids, attention_mask=mask) - @jax.jit - def transformer_step(t_params, latents, img_ids, prompt_embeds, txt_ids, vec, timestep, guidance): - return self.transformer.apply( - {"params": t_params}, - hidden_states=latents, - img_ids=img_ids, - encoder_hidden_states=prompt_embeds, - txt_ids=txt_ids, - pooled_projections=vec, - timestep=timestep, - guidance=guidance, - ) + if isinstance(self.transformer, nnx.Module): + graphdef, _, rest = nnx.split(self.transformer, nnx.Param, ...) + + @jax.jit + def transformer_step_nnx(t_params, latents, img_ids, prompt_embeds, txt_ids, vec, timestep, guidance): + transformer = nnx.merge(graphdef, t_params, rest) + out = transformer( + hidden_states=latents, + img_ids=img_ids, + encoder_hidden_states=prompt_embeds, + txt_ids=txt_ids, + pooled_projections=vec, + timestep=timestep, + guidance=guidance, + return_dict=False, + )[0] + return Transformer2DModelOutput(sample=out) + + self._jitted_transformer_step = transformer_step_nnx + else: - @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 + def transformer_step(t_params, latents, img_ids, prompt_embeds, txt_ids, vec, timestep, guidance): + return self.transformer.apply( + {"params": t_params}, + hidden_states=latents, + img_ids=img_ids, + encoder_hidden_states=prompt_embeds, + txt_ids=txt_ids, + pooled_projections=vec, + timestep=timestep, + guidance=guidance, + ) + + self._jitted_transformer_step = transformer_step + + @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 +271,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 +324,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 not prompts: + raise ValueError("Prompt must be provided to FlaxFlux2KleinPipeline") + if 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 +376,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 +391,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 +407,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 +458,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 +475,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 +486,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..3f1ae6186 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 @@ -58,6 +59,7 @@ def test_flux2klein_4b_smoke(self): f"prompt={PROMPT}", "height=512", "width=512", + f"per_device_batch_size={1.0 / jax.device_count()}", "batch_size=1", "seed=42", "ici_fsdp_parallelism=-1", @@ -101,6 +103,7 @@ def test_flux2klein_9b_smoke(self): f"prompt={PROMPT}", "height=512", "width=512", + f"per_device_batch_size={1.0 / jax.device_count()}", "batch_size=1", "seed=42", "ici_fsdp_parallelism=-1", @@ -117,7 +120,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_4b.png b/src/maxdiffusion/tests/images/ref_flux2klein_4b.png index 0eba6a072..e6a30c408 100644 Binary files a/src/maxdiffusion/tests/images/ref_flux2klein_4b.png and b/src/maxdiffusion/tests/images/ref_flux2klein_4b.png differ diff --git a/src/maxdiffusion/tests/images/ref_flux2klein_9b.png b/src/maxdiffusion/tests/images/ref_flux2klein_9b.png index 594464a8f..704d0fee8 100644 Binary files a/src/maxdiffusion/tests/images/ref_flux2klein_9b.png and b/src/maxdiffusion/tests/images/ref_flux2klein_9b.png differ diff --git a/src/maxdiffusion/tests/nnx_flux2klein_test.py b/src/maxdiffusion/tests/nnx_flux2klein_test.py index 5ae88d8eb..9eb9d1f41 100644 --- a/src/maxdiffusion/tests/nnx_flux2klein_test.py +++ b/src/maxdiffusion/tests/nnx_flux2klein_test.py @@ -23,7 +23,7 @@ import jax.numpy as jnp from flax import nnx -from maxdiffusion.models.flux.transformers.transformer_flux_flax import NNXFluxTransformer2DModel +from maxdiffusion.models.flux.transformers.transformer_flux_flax import NNXFlux2KleinTransformer2DModel from maxdiffusion.models.qwen3_flax import FlaxQwen3Config, NNXFlaxQwen3Model from maxdiffusion.models.vae_flax import NNXFlaxAutoencoderKL from maxdiffusion.models.embeddings_flax import NNXCombinedTimestepGuidanceTextProjEmbeddings @@ -83,9 +83,9 @@ def test_nnx_vae_decoder_forward(self): def test_nnx_flux_transformer_forward(self): rngs = nnx.Rngs(0) - transformer = NNXFluxTransformer2DModel( + transformer = NNXFlux2KleinTransformer2DModel( rngs=rngs, - in_channels=16, + in_channels=128, num_layers=1, num_single_layers=2, attention_head_dim=128, @@ -93,15 +93,16 @@ def test_nnx_flux_transformer_forward(self): joint_attention_dim=128, pooled_projection_dim=128, guidance_embeds=True, - axes_dim=(16, 56, 56), + axes_dim=(32, 32, 32, 32), + theta=2000.0, ) - hidden_states = jnp.ones((1, 64, 16)) + hidden_states = jnp.ones((1, 64, 128)) encoder_hidden_states = jnp.ones((1, 16, 128)) pooled_projections = jnp.ones((1, 128)) timestep = jnp.array([100.0]) guidance = jnp.array([3.5]) - img_ids = jnp.zeros((64, 3)) - txt_ids = jnp.zeros((16, 3)) + img_ids = jnp.zeros((64, 4)) + txt_ids = jnp.zeros((16, 4)) output = transformer( hidden_states=hidden_states, @@ -111,8 +112,9 @@ def test_nnx_flux_transformer_forward(self): img_ids=img_ids, txt_ids=txt_ids, guidance=guidance, - ) - self.assertEqual(output.shape, (1, 64, 16)) + return_dict=False, + )[0] + self.assertEqual(output.shape, (1, 64, 128)) if __name__ == "__main__":