You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
***Objective**: Onboard the `Flux.2-klein-4B` model (currently implemented in PyTorch's `diffusers` library) into this `maxdiffusion` repository so it can run with JAX+TPU support.
5
+
***Reference Implementation**: We are porting and improving upon the PyTorch reference implementation: [pipeline_flux2_klein.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux2/pipeline_flux2_klein.py).
6
+
7
+
### Key Development Files
8
+
***Pipeline Entry Point**: `src/maxdiffusion/generate_flux2klein.py`. This is where we load configurations, load weights, stitch together all model blocks, run the image generation pipeline, apply VAE Batch Normalization, and run the JAX VAE Decoder.
9
+
***Component Testing**: `src/maxdiffusion/tests/generate_flux2klein_test.py`. This is where we write granular unit tests verifying the scheduler, RoPE position grids, packing/unpacking, individual attention blocks, E2E transformer, and the VAE decoder.
10
+
11
+
### Completed Milestones (⚠️ LOST CHECKPOINT - ACTIVE RECOVERY IN PROGRESS)
12
+
> [!IMPORTANT]
13
+
> The parity milestones listed below were achieved on a previous repository checkpoint that is no longer available. We are currently working to recover the codebase to this state from scratch.
14
+
1.**4-Step Denoising Parity**: [In Progress] Recovering parity between the JAX transformer + FlowMatch scheduler loop and the PyTorch reference.
15
+
2.**VAE Decoder Port**: [In Progress] Verification of `FlaxAutoencoderKL` decoder mapping.
If you are picking up this project, your immediate priority tasks are:
25
+
26
+
1.**Task 1: Batched Generation ($B > 1$)**
27
+
* Verify the pipeline under `batch_size > 1` (parallel prompt and image generation).
28
+
* Ensure coordinate ID replication (`jnp.repeat`) and parallel latent unpacking loop work flawlessly without collapsing dimensions.
29
+
**Note*: Flux was **not** trained with attention masks (verified by Hugging Face `diffusers` codebase search), so do **not** attempt to implement an attention mask; let the model attend to the padded sequence naturally, as this is how it maintains its learned representations!
* Verify JAX generation for non-square aspect ratios (e.g. 1024x768).
32
+
* To prevent slow JAX/XLA re-compilation runs in production when the resolution changes, implement a **static shape bucketing strategy** (e.g. compiling for a few standard sizes like 512x512, 768x512, 1024x768, and padding inputs).
* Port the VAE Encoder block (`FlaxEncoder` inside `vae_flax.py`) to JAX and write its weights mapping function.
35
+
* Implement the inverse Batch Normalization step on encoded latents and verify the entire roundtrip (image $\rightarrow$ latents $\rightarrow$ image) is mathematically lossless.
36
+
4.**Task 4: ControlNet & LoRA Adapter Merging**
37
+
* Verify how to dynamically load LoRA weights and merge them into the main parameter PyTrees (`vae_params` and `transformer_params`) efficiently without triggering XLA re-compilations.
38
+
39
+
---
40
+
41
+
## ⚠️ CRITICAL WORKFLOW RULES
42
+
43
+
### 1. The Continuous Rsync Race Condition Warning
44
+
***The Problem**: The user has a continuous `rsync` script running from their local workspace to the remote TPU VM (`local -> VM`).
45
+
***The Risk**: If you generate any large file on the VM (like a new 1.8GB diagnostic `.npz` bundle, or a generated image), the local workspace won't have it. During the next `rsync` pass, the user's script will see the mismatch and **overwrite or delete** your newly generated file on the VM with the old/missing local one!
46
+
***The Rule**: As soon as you generate a new diagnostic bundle or output on the VM, you **must immediately run a `gcloud compute tpus tpu-vm scp` command to download it to your local workspace**. Once it is local, the `rsync` script will see both environments are identical and won't touch it.
47
+
48
+
### 2. Testing & Execution Environment
49
+
***Target VM**: Run all code and tests exclusively on the remote TPU VM `ameypasarkar-tpu` in zone `southamerica-west1-a` (Project: `cloud-tpu-inference-test`).
50
+
***No Local Runs**: Do not attempt to run the model or tests in your local workspace environment.
51
+
***Permissions**: Always ask the user for explicit permission before running any tests or pipeline scripts on the TPU VM.
*(Note: Always prepend `source ~/.bashrc` to ensure user-specific environment variables like `HF_HOME` and Hugging Face authentication tokens are correctly loaded).*
60
+
61
+
### 3. Git Workflow
62
+
***Branch Constraint**: Work exclusively on the `flux2klein-onboarding` branch.
63
+
***Commit History**: Create individual, focused commits per task/fix. Do NOT squash commits into 1 unless explicitly requested by the user.
64
+
***Code Push**: Never push code to the remote repository without explicit user permission.
65
+
66
+
### 4. Precision Policy: Debugging vs Production
67
+
***For Parity Verification**: Set `jax_default_matmul_precision = "highest"` and load weights in`float32`. This removes TPU hardware-level `bfloat16` rounding noise, allowing you to isolate structural bugs by achieving clean $10^{-6}$ differences. (Note: Only feasible for resolutions up to 512x512 due to memory limits).
68
+
***For Production/Inference & High Resolutions (e.g. 1024x1024)**: Set `weights_dtype: 'bfloat16'` and `activations_dtype: 'bfloat16'`in the config, and let JAX use default matmul precision. This activates the TPU's hardware matrix units, giving maximum speed and efficiency.
69
+
* **TPU HBM Memory Optimization**: Running 1024x1024 generation in float32 completely saturates the 32GB HBM of a single TPU v6e. You **must** run in `bfloat16` and use a recursive, leaf-by-leaf in-place parameter casting strategy (`cast_dict_to_bfloat16_inplace` with active Python `gc.collect()`) during weight conversion to avoid `RESOURCE_EXHAUSTED` OOM crashes.
0 commit comments