Skip to content

Commit 5d9fdef

Browse files
Merge pull request #418 from AI-Hypercomputer:add-sd15-support
PiperOrigin-RevId: 933185351
2 parents ee00dce + 164ca87 commit 5d9fdef

5 files changed

Lines changed: 354 additions & 25 deletions

File tree

src/maxdiffusion/checkpointing/base_stable_diffusion_checkpointer.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ def load_diffusers_checkpoint(self):
209209
split_head_dim=self.config.split_head_dim,
210210
norm_num_groups=self.config.norm_num_groups,
211211
attention_kernel=self.config.attention,
212+
flash_min_seq_length=getattr(self.config, "flash_min_seq_length", 4096),
212213
flash_block_sizes=flash_block_sizes,
213214
mesh=self.mesh,
214215
precision=precision,
@@ -220,6 +221,7 @@ def load_diffusers_checkpoint(self):
220221
split_head_dim=self.config.split_head_dim,
221222
norm_num_groups=self.config.norm_num_groups,
222223
attention_kernel=self.config.attention,
224+
flash_min_seq_length=getattr(self.config, "flash_min_seq_length", 4096),
223225
flash_block_sizes=flash_block_sizes,
224226
dtype=self.activations_dtype,
225227
weights_dtype=self.weights_dtype,
@@ -279,6 +281,7 @@ def load_checkpoint(self, step=None, scheduler_class=None):
279281
split_head_dim=self.config.split_head_dim,
280282
norm_num_groups=self.config.norm_num_groups,
281283
attention_kernel=self.config.attention,
284+
flash_min_seq_length=getattr(self.config, "flash_min_seq_length", 4096),
282285
flash_block_sizes=flash_block_sizes,
283286
mesh=self.mesh,
284287
precision=precision,

src/maxdiffusion/configs/README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,13 @@
22

33
This directory contains model configuration for different Stable Diffusion models.
44

5+
## Stable Diffusion 1.5
6+
7+
base15.yml - used for training and inference using [stable-diffusion-v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5).
8+
The upstream checkpoint ships PyTorch weights only, so this config sets `from_pt: True`; point
9+
`pretrained_model_name_or_path` at a local diffusers snapshot for offline runs. It defaults to the
10+
checkpoint's PNDM scheduler (epsilon prediction) to match the reference inference path.
11+
512
## Stable Diffusion 2.1
613

714
base21.yml - used for training and inference using [stable-diffusion-2-1](https://huggingface.co/stabilityai/stable-diffusion-2-1)
Lines changed: 279 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,279 @@
1+
# Copyright 2025 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+
# Stable Diffusion 1.5 base config.
16+
#
17+
# SD 1.5 shares the same architecture as SD 1.4 (CLIP ViT-L/14 text encoder,
18+
# 860M UNet, AutoencoderKL) and only differs by the trained weights, so this
19+
# config mirrors base14.yml and points at the v1-5 checkpoint. The upstream
20+
# checkpoint only ships PyTorch weights, so from_pt is True by default; override
21+
# pretrained_model_name_or_path to a local diffusers snapshot for offline runs.
22+
23+
# This sentinel is a reminder to choose a real run name.
24+
run_name: ''
25+
26+
metrics_file: "" # for testing, local file that stores scalar metrics. If empty, no metrics are written.
27+
# If true save metrics such as loss and TFLOPS to GCS in {base_output_directory}/{run_name}/metrics/
28+
write_metrics: True
29+
gcs_metrics: True
30+
31+
# For testing, local file that stores function timing metrics such as state creation and compilation.
32+
# If empty, no metrics are written.
33+
timing_metrics_file: ""
34+
write_timing_metrics: True
35+
36+
# If true save config to GCS in {base_output_directory}/{run_name}/
37+
save_config_to_gcs: False
38+
log_period: 10000000000 # Flushes Tensorboard
39+
40+
pretrained_model_name_or_path: 'stable-diffusion-v1-5/stable-diffusion-v1-5'
41+
unet_checkpoint: ''
42+
# The canonical v1-5 repo only publishes the main (PyTorch) revision.
43+
revision: 'main'
44+
45+
# This will convert the weights to this dtype.
46+
weights_dtype: 'float32'
47+
# This sets the layer's dtype in the model. Ex: nn.Dense(dtype=activations_dtype)
48+
activations_dtype: 'bfloat16'
49+
50+
# matmul and conv precision from https://jax.readthedocs.io/en/latest/jax.lax.html#jax.lax.Precision
51+
# Options are "DEFAULT", "HIGH", "HIGHEST"
52+
# fp32 activations and fp32 weights with HIGHEST will provide the best precision
53+
# at the cost of time.
54+
precision: "DEFAULT"
55+
56+
# if False state is not jitted and instead replicate is called. This is good for debugging on single host
57+
# It must be True for multi-host.
58+
jit_initializers: True
59+
60+
# Set true to load weights from pytorch. The v1-5 checkpoint is PyTorch-only.
61+
from_pt: True
62+
split_head_dim: True
63+
attention: 'tokamax_flash' # Supported attention: dot_product, flash, tokamax_flash
64+
# Minimum Q/K/V sequence length required to use flash attention. For SD 1.5
65+
# 1024x1024 inference, the two largest self-attention lengths are 16384 and
66+
# 4096, while cross-attention falls back to dot_product because text KV length
67+
# is 77.
68+
flash_min_seq_length: 4096
69+
# If mask_padding_tokens is True, we pass in segment ids to splash attention to avoid attending to padding tokens.
70+
# Else we do not pass in segment ids and on vpu bound hardware like trillium this is faster.
71+
# However, when padding tokens are significant, this will lead to worse quality and should be set to True.
72+
mask_padding_tokens: True
73+
# Maxdiffusion has 2 types of attention sharding strategies:
74+
# 1. attention_sharding_uniform = True : same sequence sharding rules applied for q in both (self and cross attention)
75+
# 2. attention_sharding_uniform = False : Heads are sharded uniformly across devices for self attention
76+
# while sequence is sharded in cross attention q.
77+
attention_sharding_uniform: True
78+
flash_block_sizes: {
79+
"block_q" : 2048,
80+
"block_kv_compute" : 1024,
81+
"block_kv" : 2048,
82+
"block_q_dkv" : 2048,
83+
"block_kv_dkv" : 2048,
84+
"block_kv_dkv_compute" : 1024
85+
}
86+
# GroupNorm groups
87+
norm_num_groups: 32
88+
89+
# If train_new_unet, unet weights will be randomly initialized to train the unet from scratch
90+
# else they will be loaded from pretrained_model_name_or_path
91+
train_new_unet: False
92+
93+
# train text_encoder
94+
train_text_encoder: False
95+
text_encoder_learning_rate: 4.25e-6
96+
97+
# https://arxiv.org/pdf/2305.08891.pdf
98+
snr_gamma: -1.0
99+
100+
timestep_bias: {
101+
# a value of later will increase the frequence of the model's final training steps.
102+
# none, earlier, later, range
103+
strategy: "none",
104+
# multiplier for bias, a value of 2.0 will double the weight of the bias, 0.5 will halve it.
105+
multiplier: 1.0,
106+
# when using strategy=range, the beginning (inclusive) timestep to bias.
107+
begin: 0,
108+
# when using strategy=range, the final step (inclusive) to bias.
109+
end: 1000,
110+
# portion of timesteps to bias.
111+
# 0.5 will bias one half of the timesteps. Value of strategy determines
112+
# whether the biased portions are in the earlier or later timesteps.
113+
portion: 0.25
114+
}
115+
116+
# SD 1.5 uses a PNDM sampler with epsilon prediction and leading timestep
117+
# spacing. These mirror the checkpoint's scheduler_config.json so generation
118+
# matches the diffusers/reference defaults.
119+
diffusion_scheduler_config: {
120+
_class_name: 'FlaxPNDMScheduler',
121+
prediction_type: 'epsilon',
122+
rescale_zero_terminal_snr: False,
123+
timestep_spacing: 'leading'
124+
}
125+
126+
# Hardware
127+
hardware: 'tpu' # Supported hardware types are 'tpu', 'gpu'
128+
skip_jax_distributed_system: False
129+
130+
base_output_directory: ""
131+
132+
# Parallelism
133+
mesh_axes: ['data', 'fsdp', 'context', 'tensor']
134+
135+
# batch : batch dimension of data and activations
136+
# hidden :
137+
# embed : attention qkv dense layer hidden dim named as embed
138+
# heads : attention head dim = num_heads * head_dim
139+
# length : attention sequence length
140+
# temb_in : dense.shape[0] of resnet dense before conv
141+
# out_c : dense.shape[1] of resnet dense before conv
142+
# out_channels : conv.shape[-1] activation
143+
# keep_1 : conv.shape[0] weight
144+
# keep_2 : conv.shape[1] weight
145+
# conv_in : conv.shape[2] weight
146+
# conv_out : conv.shape[-1] weight
147+
logical_axis_rules: [
148+
['batch', 'data'],
149+
['activation_batch', ['data','fsdp']],
150+
['activation_heads', 'tensor'],
151+
['activation_kv', 'tensor'],
152+
['embed','fsdp'],
153+
['heads', 'tensor'],
154+
['conv_batch', ['data','fsdp']],
155+
['out_channels', 'tensor'],
156+
['conv_out', 'fsdp'],
157+
]
158+
data_sharding: [['data', 'fsdp', 'context', 'tensor']]
159+
160+
# One axis for each parallelism type may hold a placeholder (-1)
161+
# value to auto-shard based on available slices and devices.
162+
# By default, product of the DCN axes should equal number of slices
163+
# and product of the ICI axes should equal number of devices per slice.
164+
dcn_data_parallelism: -1 # recommended DCN axis to be auto-sharded
165+
dcn_fsdp_parallelism: 1
166+
dcn_context_parallelism: 1
167+
dcn_tensor_parallelism: 1
168+
ici_data_parallelism: -1 # recommended ICI axis to be auto-sharded for TPUv5e
169+
ici_fsdp_parallelism: 1 # recommended ICI axis to be auto-sharded
170+
ici_context_parallelism: 1
171+
ici_tensor_parallelism: 1
172+
173+
allow_split_physical_axes: False
174+
175+
# Dataset
176+
# Replace with dataset path or train_data_dir. One has to be set.
177+
dataset_name: 'diffusers/pokemon-gpt4-captions'
178+
train_split: 'train'
179+
dataset_type: 'tf'
180+
cache_latents_text_encoder_outputs: True
181+
# cache_latents_text_encoder_outputs only apply to dataset_type="tf",
182+
# only apply to small dataset that fits in memory
183+
# prepare image latents and text encoder outputs
184+
# Reduce memory consumption and reduce step time during training
185+
# transformed dataset is saved at dataset_save_location
186+
dataset_save_location: '/tmp/pokemon-gpt4-captions_sd15'
187+
train_data_dir: ''
188+
dataset_config_name: ''
189+
jax_cache_dir: ''
190+
hf_data_dir: ''
191+
hf_train_files: ''
192+
hf_access_token: ''
193+
image_column: 'image'
194+
caption_column: 'text'
195+
resolution: 512
196+
center_crop: False
197+
random_flip: False
198+
# If cache_latents_text_encoder_outputs is True
199+
# the num_proc is set to 1
200+
tokenize_captions_num_proc: 4
201+
transform_images_num_proc: 4
202+
reuse_example_batch: False
203+
enable_data_shuffling: True
204+
205+
# checkpoint every number of samples, -1 means don't checkpoint.
206+
checkpoint_every: -1
207+
# enables one replica to read the ckpt then broadcast to the rest
208+
enable_single_replica_ckpt_restoring: False
209+
210+
# Training loop
211+
learning_rate: 1.e-7
212+
scale_lr: False
213+
max_train_samples: -1
214+
# max_train_steps takes priority over num_train_epochs.
215+
max_train_steps: 800
216+
seed: 0
217+
# Output directory
218+
# Create a GCS bucket, e.g. my-maxdiffusion-outputs and set this to "gs://my-maxdiffusion-outputs/"
219+
output_dir: ''
220+
per_device_batch_size: 1
221+
222+
warmup_steps_fraction: 0.0
223+
learning_rate_schedule_steps: -1 # By default the length of the schedule is set to the number of steps.
224+
225+
# However you may choose a longer schedule (learning_rate_schedule_steps > steps), in which case the training will end before
226+
# dropping fully down. Or you may choose a shorter schedule, where the unspecified steps will have a learning rate of 0.
227+
228+
# AdamW optimizer parameters
229+
adam_b1: 0.9 # Exponential decay rate to track the first moment of past gradients.
230+
adam_b2: 0.999 # Exponential decay rate to track the second moment of past gradients.
231+
adam_eps: 1.e-8 # A small constant applied to denominator outside of the square root.
232+
adam_weight_decay: 1.e-2 # AdamW Weight decay
233+
opt_enable_grad_clipping: False
234+
max_grad_value: 1.0
235+
opt_enable_grad_global_norm_clipping: False
236+
max_grad_norm: 1.0
237+
238+
enable_profiler: False
239+
# Skip first n steps for profiling, to omit things like compilation and to give
240+
# the iteration time a chance to stabilize.
241+
skip_first_n_steps_for_profiler: 1
242+
profiler_steps: 5
243+
244+
# Generation parameters
245+
prompt: "A magical castle in the middle of a forest, artistic drawing"
246+
negative_prompt: "purple, red"
247+
guidance_scale: 7.5
248+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
249+
guidance_rescale: 0.0
250+
# SD 1.5 reference inference default.
251+
num_inference_steps: 20
252+
253+
enable_mllog: False
254+
255+
# controlnet
256+
controlnet_model_name_or_path: 'lllyasviel/sd-controlnet-canny'
257+
controlnet_from_pt: True
258+
controlnet_conditioning_scale: 1.0
259+
controlnet_image: 'https://huggingface.co/datasets/YiYiXu/test-doc-assets/resolve/main/blog_post_cell_10_output_0.jpeg'
260+
261+
# dreambooth - this script always uses prior preservation.
262+
instance_data_dir: ''
263+
class_data_dir: ''
264+
instance_prompt: ''
265+
class_prompt: ''
266+
prior_loss_weight: 1.0
267+
num_class_images: 100
268+
# If true, set dataset_save_location.
269+
cache_dreambooth_dataset: False
270+
quantization: ''
271+
# Shard the range finding operation for quantization. By default this is set to number of slices.
272+
quantization_local_shard_count: -1
273+
use_qwix_quantization: False
274+
compile_topology_num_slices: -1 # Number of target slices, set to a positive integer.
275+
276+
# ML Diagnostics settings
277+
enable_ml_diagnostics: False
278+
profiler_gcs_path: ""
279+
enable_ondemand_xprof: False

0 commit comments

Comments
 (0)