Skip to content

Commit 64450df

Browse files
committed
Onboard Flux.2-klein model family (4B/9B) into MaxDiffusion (JAX+TPU)
1 parent e0ba26c commit 64450df

18 files changed

Lines changed: 4699 additions & 62 deletions

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -723,6 +723,22 @@ We added ring attention support for Wan models. Below are the stats for one `720
723723
```bash
724724
python src/maxdiffusion/generate_flux.py src/maxdiffusion/configs/base_flux_schnell.yml jax_cache_dir=/tmp/cache_dir run_name=flux_test output_dir=/tmp/ prompt="photograph of an electronics chip in the shape of a race car with trillium written on its side" per_device_batch_size=1 ici_data_parallelism=1 ici_fsdp_parallelism=-1 offload_encoders=False
725725
```
726+
727+
### Flux.2-Klein (4B & 9B)
728+
729+
Flux.2-Klein provides ultra-fast 4-step image generation using Qwen3 text embeddings and FLUX.2 transformer blocks.
730+
731+
Flux.2-Klein 4B:
732+
733+
```bash
734+
python src/maxdiffusion/generate_flux2klein.py src/maxdiffusion/configs/base_flux2klein.yml run_name=flux2klein_4b prompt="A detailed vector illustration of a robotic hummingbird"
735+
```
736+
737+
Flux.2-Klein 9B:
738+
739+
```bash
740+
python src/maxdiffusion/generate_flux2klein.py src/maxdiffusion/configs/base_flux2klein_9B.yml run_name=flux2klein_9b prompt="A detailed vector illustration of a robotic hummingbird"
741+
```
726742
## Fused Attention for GPU:
727743
Fused Attention for GPU is supported via TransformerEngine. Installation instructions:
728744

Lines changed: 275 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,275 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# This sentinel is a reminder to choose a real run name.
16+
run_name: 'flux2klein_test_run'
17+
18+
metrics_file: "" # for testing, local file that stores scalar metrics. If empty, no metrics are written.
19+
# If true save metrics such as loss and TFLOPS to GCS in {base_output_directory}/{run_name}/metrics/
20+
write_metrics: True
21+
22+
timing_metrics_file: "" # for testing, local file that stores function timing metrics such as state creation, compilation. If empty, no metrics are written.
23+
write_timing_metrics: True
24+
25+
gcs_metrics: False
26+
# If true save config to GCS in {base_output_directory}/{run_name}/
27+
save_config_to_gcs: False
28+
log_period: 100
29+
30+
pretrained_model_name_or_path: 'black-forest-labs/FLUX.2-klein-4B'
31+
clip_model_name_or_path: 'ariG23498/clip-vit-large-patch14-text-flax'
32+
t5xxl_model_name_or_path: 'ariG23498/t5-v1-1-xxl-flax'
33+
34+
# Flux params
35+
flux_name: "flux2klein"
36+
scale_shift_order: "scale_shift"
37+
use_latents: False
38+
latents_path: ""
39+
max_sequence_length: 512
40+
time_shift: True
41+
base_shift: 0.5
42+
max_shift: 1.15
43+
44+
45+
unet_checkpoint: ''
46+
revision: 'refs/pr/95'
47+
# This will convert the weights to this dtype.
48+
# When running inference on TPUv5e, use weights_dtype: 'bfloat16'
49+
weights_dtype: 'bfloat16'
50+
# This sets the layer's dtype in the model. Ex: nn.Dense(dtype=activations_dtype)
51+
activations_dtype: 'bfloat16'
52+
53+
# matmul and conv precision from https://jax.readthedocs.io/en/latest/jax.lax.html#jax.lax.Precision
54+
# Options are "DEFAULT", "HIGH", "HIGHEST"
55+
# fp32 activations and fp32 weights with HIGHEST will provide the best precision
56+
# at the cost of time.
57+
precision: "DEFAULT"
58+
59+
# if False state is not jitted and instead replicate is called. This is good for debugging on single host
60+
# It must be True for multi-host.
61+
jit_initializers: True
62+
63+
# Set true to load weights from pytorch
64+
from_pt: True
65+
split_head_dim: True
66+
attention: 'flash' # Supported attention: dot_product, flash, cudnn_flash_te
67+
# If mask_padding_tokens is True, we pass in segment ids to splash attention to avoid attending to padding tokens.
68+
# Else we do not pass in segment ids and on vpu bound hardware like trillium this is faster.
69+
# However, when padding tokens are significant, this will lead to worse quality and should be set to True.
70+
mask_padding_tokens: True
71+
# Maxdiffusion has 2 types of attention sharding strategies:
72+
# 1. attention_sharding_uniform = True : same sequence sharding rules applied for q in both (self and cross attention)
73+
# 2. attention_sharding_uniform = False : Heads are sharded uniformly across devices for self attention while sequence is sharded
74+
# in cross attention q.
75+
attention_sharding_uniform: True
76+
77+
flash_block_sizes: {}
78+
# GroupNorm groups
79+
norm_num_groups: 32
80+
81+
# If train_new_flux, flux weights will be randomly initialized to train flux from scratch
82+
# else they will be loaded from pretrained_model_name_or_path
83+
train_new_flux: False
84+
85+
# train text_encoder - Currently not supported for SDXL
86+
train_text_encoder: False
87+
text_encoder_learning_rate: 4.25e-6
88+
89+
# https://arxiv.org/pdf/2305.08891.pdf
90+
snr_gamma: -1.0
91+
92+
timestep_bias: {
93+
# a value of later will increase the frequence of the model's final training steps.
94+
# none, earlier, later, range
95+
strategy: "none",
96+
# multiplier for bias, a value of 2.0 will double the weight of the bias, 0.5 will halve it.
97+
multiplier: 1.0,
98+
# when using strategy=range, the beginning (inclusive) timestep to bias.
99+
begin: 0,
100+
# when using strategy=range, the final step (inclusive) to bias.
101+
end: 1000,
102+
# portion of timesteps to bias.
103+
# 0.5 will bias one half of the timesteps. Value of strategy determines
104+
# whether the biased portions are in the earlier or later timesteps.
105+
portion: 0.25
106+
}
107+
108+
# Override parameters from checkpoints's scheduler.
109+
diffusion_scheduler_config: {
110+
_class_name: 'FlaxEulerDiscreteScheduler',
111+
prediction_type: 'epsilon',
112+
rescale_zero_terminal_snr: False,
113+
timestep_spacing: 'trailing'
114+
}
115+
116+
# Output directory
117+
# Create a GCS bucket, e.g. my-maxtext-outputs and set this to "gs://my-maxtext-outputs/"
118+
base_output_directory: ""
119+
120+
# Hardware
121+
hardware: 'tpu' # Supported hardware types are 'tpu', 'gpu'
122+
skip_jax_distributed_system: False
123+
124+
# Parallelism
125+
mesh_axes: ['data', 'fsdp', 'context', 'tensor']
126+
127+
# batch : batch dimension of data and activations
128+
# hidden :
129+
# embed : attention qkv dense layer hidden dim named as embed
130+
# heads : attention head dim = num_heads * head_dim
131+
# length : attention sequence length
132+
# temb_in : dense.shape[0] of resnet dense before conv
133+
# out_c : dense.shape[1] of resnet dense before conv
134+
# out_channels : conv.shape[-1] activation
135+
# keep_1 : conv.shape[0] weight
136+
# keep_2 : conv.shape[1] weight
137+
# conv_in : conv.shape[2] weight
138+
# conv_out : conv.shape[-1] weight
139+
logical_axis_rules: [
140+
['batch', 'data'],
141+
['activation_batch', ['data','fsdp']],
142+
['activation_heads', 'tensor'],
143+
['activation_kv', 'tensor'],
144+
['mlp','tensor'],
145+
['embed','fsdp'],
146+
['heads', 'tensor'],
147+
['conv_batch', ['data','fsdp']],
148+
['out_channels', 'tensor'],
149+
['conv_out', 'fsdp'],
150+
]
151+
data_sharding: [['data', 'fsdp', 'context', 'tensor']]
152+
153+
# One axis for each parallelism type may hold a placeholder (-1)
154+
# value to auto-shard based on available slices and devices.
155+
# By default, product of the DCN axes should equal number of slices
156+
# and product of the ICI axes should equal number of devices per slice.
157+
dcn_data_parallelism: 1 # recommended DCN axis to be auto-sharded
158+
dcn_fsdp_parallelism: -1
159+
dcn_context_parallelism: 1
160+
dcn_tensor_parallelism: 1
161+
ici_data_parallelism: 1
162+
ici_fsdp_parallelism: -1
163+
ici_context_parallelism: 1
164+
ici_tensor_parallelism: 1
165+
166+
allow_split_physical_axes: False
167+
168+
# Dataset
169+
# Replace with dataset path or train_data_dir. One has to be set.
170+
dataset_name: 'diffusers/pokemon-gpt4-captions'
171+
train_split: 'train'
172+
dataset_type: 'tfrecord' # Options: 'tfrecord', 'hf', 'tf', 'grain', 'synthetic'
173+
cache_latents_text_encoder_outputs: True
174+
dataset_save_location: '/tmp/pokemon-gpt4-captions_xl'
175+
train_data_dir: ''
176+
dataset_config_name: ''
177+
jax_cache_dir: ''
178+
hf_data_dir: ''
179+
hf_train_files: ''
180+
hf_access_token: ''
181+
image_column: 'image'
182+
caption_column: 'text'
183+
resolution: 512
184+
center_crop: False
185+
random_flip: False
186+
tokenize_captions_num_proc: 4
187+
transform_images_num_proc: 4
188+
reuse_example_batch: False
189+
enable_data_shuffling: True
190+
191+
# checkpoint every number of samples, -1 means don't checkpoint.
192+
checkpoint_every: -1
193+
# enables one replica to read the ckpt then broadcast to the rest
194+
enable_single_replica_ckpt_restoring: False
195+
196+
# Training loop
197+
learning_rate: 1.e-5
198+
scale_lr: False
199+
max_train_samples: -1
200+
# max_train_steps takes priority over num_train_epochs.
201+
max_train_steps: 1500
202+
num_train_epochs: 1
203+
seed: 0
204+
output_dir: 'output/'
205+
output_name: "flux2klein_generated_image.png"
206+
per_device_batch_size: 1
207+
208+
warmup_steps_fraction: 0.1
209+
learning_rate_schedule_steps: -1 # By default the length of the schedule is set to the number of steps.
210+
211+
# AdamW optimizer parameters
212+
adam_b1: 0.9 # Exponential decay rate to track the first moment of past gradients.
213+
adam_b2: 0.999 # Exponential decay rate to track the second moment of past gradients.
214+
adam_eps: 1.e-8 # A small constant applied to denominator outside of the square root.
215+
adam_weight_decay: 0 # AdamW Weight decay
216+
opt_enable_grad_clipping: False
217+
max_grad_value: 1.0
218+
opt_enable_grad_global_norm_clipping: False
219+
max_grad_norm: 1.0
220+
221+
enable_profiler: False
222+
skip_first_n_steps_for_profiler: 5
223+
profiler_steps: 10
224+
profiler: ""
225+
226+
# Generation parameters
227+
prompt: "a car jumping off of a cliff with a crowd cheering"
228+
prompt_2: "A detailed vector illustration of a robotic hummingbird || A cinematic shot of a neon-lit cyberpunk street"
229+
negative_prompt: ""
230+
do_classifier_free_guidance: True
231+
guidance_scale: 4.0
232+
guidance_rescale: 0.0
233+
num_inference_steps: 4
234+
save_final_checkpoint: False
235+
236+
# SDXL Lightning parameters
237+
lightning_from_pt: True
238+
lightning_repo: ""
239+
lightning_ckpt: ""
240+
241+
# LoRA parameters
242+
lora_config: {
243+
lora_model_name_or_path: [],
244+
weight_name: [],
245+
adapter_name: [],
246+
scale: [],
247+
from_pt: []
248+
}
249+
250+
enable_mllog: False
251+
252+
#controlnet
253+
controlnet_model_name_or_path: 'diffusers/controlnet-canny-sdxl-1.0'
254+
controlnet_from_pt: True
255+
controlnet_conditioning_scale: 0.5
256+
controlnet_image: 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Google_%22G%22_logo.svg/1024px-Google_%22G%22_logo.svg.png'
257+
quantization: ''
258+
quantization_local_shard_count: -1
259+
use_qwix_quantization: False
260+
compile_topology_num_slices: -1 # Number of target slices, set to a positive integer.
261+
262+
# ML Diagnostics settings
263+
enable_ml_diagnostics: False
264+
profiler_gcs_path: ""
265+
enable_ondemand_xprof: False
266+
267+
# Specific additions for generate_flux2klein execution
268+
height: 1024
269+
width: 1024
270+
batch_size: 4
271+
interactive: False
272+
273+
# Note: Architecture dimensions (depth, num_double_layers, num_attention_heads) are
274+
# automatically inferred from pretrained_model_name_or_path (transformer/config.json).
275+

0 commit comments

Comments
 (0)