Skip to content

Commit 05ccabe

Browse files
committed
Onboard Flux.2-klein (4B and 9B) models with JAX/TPU support
1 parent 0956041 commit 05ccabe

17 files changed

Lines changed: 5376 additions & 857 deletions
Lines changed: 278 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
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+
max_sequence_length: 512
39+
time_shift: True
40+
base_shift: 0.5
41+
max_shift: 1.15
42+
# offloads t5 encoder after text encoding to save memory.
43+
offload_encoders: True
44+
45+
46+
unet_checkpoint: ''
47+
revision: 'refs/pr/95'
48+
# This will convert the weights to this dtype.
49+
# When running inference on TPUv5e, use weights_dtype: 'bfloat16'
50+
weights_dtype: 'bfloat16'
51+
# This sets the layer's dtype in the model. Ex: nn.Dense(dtype=activations_dtype)
52+
activations_dtype: 'bfloat16'
53+
54+
# matmul and conv precision from https://jax.readthedocs.io/en/latest/jax.lax.html#jax.lax.Precision
55+
# Options are "DEFAULT", "HIGH", "HIGHEST"
56+
# fp32 activations and fp32 weights with HIGHEST will provide the best precision
57+
# at the cost of time.
58+
precision: "DEFAULT"
59+
60+
# if False state is not jitted and instead replicate is called. This is good for debugging on single host
61+
# It must be True for multi-host.
62+
jit_initializers: True
63+
64+
# Set true to load weights from pytorch
65+
from_pt: True
66+
split_head_dim: True
67+
attention: 'flash' # Supported attention: dot_product, flash, cudnn_flash_te
68+
# If mask_padding_tokens is True, we pass in segment ids to splash attention to avoid attending to padding tokens.
69+
# Else we do not pass in segment ids and on vpu bound hardware like trillium this is faster.
70+
# However, when padding tokens are significant, this will lead to worse quality and should be set to True.
71+
mask_padding_tokens: True
72+
# Maxdiffusion has 2 types of attention sharding strategies:
73+
# 1. attention_sharding_uniform = True : same sequence sharding rules applied for q in both (self and cross attention)
74+
# 2. attention_sharding_uniform = False : Heads are sharded uniformly across devices for self attention while sequence is sharded
75+
# in cross attention q.
76+
attention_sharding_uniform: True
77+
78+
flash_block_sizes: {}
79+
# GroupNorm groups
80+
norm_num_groups: 32
81+
82+
# If train_new_flux, flux weights will be randomly initialized to train flux from scratch
83+
# else they will be loaded from pretrained_model_name_or_path
84+
train_new_flux: False
85+
86+
# train text_encoder - Currently not supported for SDXL
87+
train_text_encoder: False
88+
text_encoder_learning_rate: 4.25e-6
89+
90+
# https://arxiv.org/pdf/2305.08891.pdf
91+
snr_gamma: -1.0
92+
93+
timestep_bias: {
94+
# a value of later will increase the frequence of the model's final training steps.
95+
# none, earlier, later, range
96+
strategy: "none",
97+
# multiplier for bias, a value of 2.0 will double the weight of the bias, 0.5 will halve it.
98+
multiplier: 1.0,
99+
# when using strategy=range, the beginning (inclusive) timestep to bias.
100+
begin: 0,
101+
# when using strategy=range, the final step (inclusive) to bias.
102+
end: 1000,
103+
# portion of timesteps to bias.
104+
# 0.5 will bias one half of the timesteps. Value of strategy determines
105+
# whether the biased portions are in the earlier or later timesteps.
106+
portion: 0.25
107+
}
108+
109+
# Override parameters from checkpoints's scheduler.
110+
diffusion_scheduler_config: {
111+
_class_name: 'FlaxEulerDiscreteScheduler',
112+
prediction_type: 'epsilon',
113+
rescale_zero_terminal_snr: False,
114+
timestep_spacing: 'trailing'
115+
}
116+
117+
# Output directory
118+
# Create a GCS bucket, e.g. my-maxtext-outputs and set this to "gs://my-maxtext-outputs/"
119+
base_output_directory: ""
120+
121+
# Hardware
122+
hardware: 'tpu' # Supported hardware types are 'tpu', 'gpu'
123+
skip_jax_distributed_system: False
124+
125+
# Parallelism
126+
mesh_axes: ['data', 'fsdp', 'context', 'tensor']
127+
128+
# batch : batch dimension of data and activations
129+
# hidden :
130+
# embed : attention qkv dense layer hidden dim named as embed
131+
# heads : attention head dim = num_heads * head_dim
132+
# length : attention sequence length
133+
# temb_in : dense.shape[0] of resnet dense before conv
134+
# out_c : dense.shape[1] of resnet dense before conv
135+
# out_channels : conv.shape[-1] activation
136+
# keep_1 : conv.shape[0] weight
137+
# keep_2 : conv.shape[1] weight
138+
# conv_in : conv.shape[2] weight
139+
# conv_out : conv.shape[-1] weight
140+
logical_axis_rules: [
141+
['batch', 'data'],
142+
['activation_batch', ['data','fsdp']],
143+
['activation_heads', 'tensor'],
144+
['activation_kv', 'tensor'],
145+
['mlp','tensor'],
146+
['embed','fsdp'],
147+
['heads', 'tensor'],
148+
['conv_batch', ['data','fsdp']],
149+
['out_channels', 'tensor'],
150+
['conv_out', 'fsdp'],
151+
]
152+
data_sharding: [['data', 'fsdp', 'context', 'tensor']]
153+
154+
# One axis for each parallelism type may hold a placeholder (-1)
155+
# value to auto-shard based on available slices and devices.
156+
# By default, product of the DCN axes should equal number of slices
157+
# and product of the ICI axes should equal number of devices per slice.
158+
dcn_data_parallelism: 1 # recommended DCN axis to be auto-sharded
159+
dcn_fsdp_parallelism: -1
160+
dcn_context_parallelism: 1
161+
dcn_tensor_parallelism: 1
162+
ici_data_parallelism: 1
163+
ici_fsdp_parallelism: -1 # recommended ICI axis to be auto-sharded
164+
ici_context_parallelism: 1
165+
ici_tensor_parallelism: 1
166+
167+
allow_split_physical_axes: False
168+
169+
# Dataset
170+
# Replace with dataset path or train_data_dir. One has to be set.
171+
dataset_name: 'diffusers/pokemon-gpt4-captions'
172+
train_split: 'train'
173+
dataset_type: 'tfrecord' # Options: 'tfrecord', 'hf', 'tf', 'grain', 'synthetic'
174+
cache_latents_text_encoder_outputs: True
175+
dataset_save_location: '/tmp/pokemon-gpt4-captions_xl'
176+
train_data_dir: ''
177+
dataset_config_name: ''
178+
jax_cache_dir: '/tmp/jax_cache'
179+
hf_data_dir: ''
180+
hf_train_files: ''
181+
hf_access_token: ''
182+
image_column: 'image'
183+
caption_column: 'text'
184+
resolution: 512
185+
center_crop: False
186+
random_flip: False
187+
tokenize_captions_num_proc: 4
188+
transform_images_num_proc: 4
189+
reuse_example_batch: False
190+
enable_data_shuffling: True
191+
192+
# checkpoint every number of samples, -1 means don't checkpoint.
193+
checkpoint_every: -1
194+
# enables one replica to read the ckpt then broadcast to the rest
195+
enable_single_replica_ckpt_restoring: False
196+
197+
# Training loop
198+
learning_rate: 1.e-5
199+
scale_lr: False
200+
max_train_samples: -1
201+
# max_train_steps takes priority over num_train_epochs.
202+
max_train_steps: 1500
203+
num_train_epochs: 1
204+
seed: 0
205+
output_dir: 'output/'
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 detailed vector illustration of a robotic hummingbird || A cinematic shot of a neon-lit cyberpunk street"
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+
# 4B Architecture Dimensions
274+
depth: 20 # num_single_layers
275+
num_double_layers: 5
276+
hidden_size: 3072
277+
num_attention_heads: 24
278+

0 commit comments

Comments
 (0)