Skip to content

Commit 77900d7

Browse files
committed
Add LoRA support for WAN models
1 parent 2879a65 commit 77900d7

7 files changed

Lines changed: 1421 additions & 0 deletions

File tree

Lines changed: 347 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,347 @@
1+
# Copyright 2023 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: ''
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: 'Wan-AI/Wan2.1-T2V-14B-Diffusers'
31+
model_name: wan2.1
32+
33+
# Overrides the transformer from pretrained_model_name_or_path
34+
wan_transformer_pretrained_model_name_or_path: ''
35+
36+
unet_checkpoint: ''
37+
revision: ''
38+
# This will convert the weights to this dtype.
39+
# When running inference on TPUv5e, use weights_dtype: 'bfloat16'
40+
weights_dtype: 'bfloat16'
41+
# This sets the layer's dtype in the model. Ex: nn.Dense(dtype=activations_dtype)
42+
activations_dtype: 'bfloat16'
43+
44+
# Replicates vae across devices instead of using the model's sharding annotations for sharding.
45+
replicate_vae: False
46+
47+
# matmul and conv precision from https://jax.readthedocs.io/en/latest/jax.lax.html#jax.lax.Precision
48+
# Options are "DEFAULT", "HIGH", "HIGHEST"
49+
# fp32 activations and fp32 weights with HIGHEST will provide the best precision
50+
# at the cost of time.
51+
precision: "DEFAULT"
52+
# Use jax.lax.scan for transformer layers
53+
scan_layers: False
54+
55+
# if False state is not jitted and instead replicate is called. This is good for debugging on single host
56+
# It must be True for multi-host.
57+
jit_initializers: True
58+
59+
# Set true to load weights from pytorch
60+
from_pt: True
61+
split_head_dim: True
62+
attention: 'flash' # Supported attention: dot_product, flash, cudnn_flash_te, ring
63+
flash_min_seq_length: 4096
64+
65+
# If mask_padding_tokens is True, we pass in segment ids to splash attention to avoid attending to padding tokens.
66+
# Else we do not pass in segment ids and on vpu bound hardware like trillium this is faster.
67+
# However, when padding tokens are significant, this will lead to worse quality and should be set to True.
68+
mask_padding_tokens: True
69+
# Maxdiffusion has 2 types of attention sharding strategies:
70+
# 1. attention_sharding_uniform = True : same sequence sharding rules applied for q in both (self and cross attention)
71+
# 2. attention_sharding_uniform = False : Heads are sharded uniformly across devices for self attention while sequence is sharded
72+
# in cross attention q.
73+
attention_sharding_uniform: True
74+
dropout: 0.1
75+
76+
#flash_block_sizes: {
77+
# "block_q" : 1024,
78+
# "block_kv_compute" : 256,
79+
# "block_kv" : 1024,
80+
# "block_q_dkv" : 1024,
81+
# "block_kv_dkv" : 1024,
82+
# "block_kv_dkv_compute" : 256,
83+
# "block_q_dq" : 1024,
84+
# "block_kv_dq" : 1024
85+
#}
86+
# Use on v6e
87+
flash_block_sizes: {
88+
"block_q" : 3024,
89+
"block_kv_compute" : 1024,
90+
"block_kv" : 2048,
91+
"block_q_dkv" : 3024,
92+
"block_kv_dkv" : 2048,
93+
"block_kv_dkv_compute" : 2048,
94+
"block_q_dq" : 3024,
95+
"block_kv_dq" : 2048,
96+
"use_fused_bwd_kernel": False,
97+
}
98+
# GroupNorm groups
99+
norm_num_groups: 32
100+
101+
# train text_encoder - Currently not supported for SDXL
102+
train_text_encoder: False
103+
text_encoder_learning_rate: 4.25e-6
104+
105+
# https://arxiv.org/pdf/2305.08891.pdf
106+
snr_gamma: -1.0
107+
108+
timestep_bias: {
109+
# a value of later will increase the frequence of the model's final training steps.
110+
# none, earlier, later, range
111+
strategy: "none",
112+
# multiplier for bias, a value of 2.0 will double the weight of the bias, 0.5 will halve it.
113+
multiplier: 1.0,
114+
# when using strategy=range, the beginning (inclusive) timestep to bias.
115+
begin: 0,
116+
# when using strategy=range, the final step (inclusive) to bias.
117+
end: 1000,
118+
# portion of timesteps to bias.
119+
# 0.5 will bias one half of the timesteps. Value of strategy determines
120+
# whether the biased portions are in the earlier or later timesteps.
121+
portion: 0.25
122+
}
123+
124+
# Override parameters from checkpoints's scheduler.
125+
diffusion_scheduler_config: {
126+
_class_name: 'FlaxEulerDiscreteScheduler',
127+
prediction_type: 'epsilon',
128+
rescale_zero_terminal_snr: False,
129+
timestep_spacing: 'trailing'
130+
}
131+
132+
# Output directory
133+
# Create a GCS bucket, e.g. my-maxtext-outputs and set this to "gs://my-maxtext-outputs/"
134+
base_output_directory: ""
135+
136+
# Hardware
137+
hardware: 'tpu' # Supported hardware types are 'tpu', 'gpu'
138+
skip_jax_distributed_system: False
139+
140+
# Parallelism
141+
mesh_axes: ['data', 'fsdp', 'tensor']
142+
143+
# batch : batch dimension of data and activations
144+
# hidden :
145+
# embed : attention qkv dense layer hidden dim named as embed
146+
# heads : attention head dim = num_heads * head_dim
147+
# length : attention sequence length
148+
# temb_in : dense.shape[0] of resnet dense before conv
149+
# out_c : dense.shape[1] of resnet dense before conv
150+
# out_channels : conv.shape[-1] activation
151+
# keep_1 : conv.shape[0] weight
152+
# keep_2 : conv.shape[1] weight
153+
# conv_in : conv.shape[2] weight
154+
# conv_out : conv.shape[-1] weight
155+
logical_axis_rules: [
156+
['batch', 'data'],
157+
['activation_batch', 'data'],
158+
['activation_self_attn_heads', ['fsdp', 'tensor']],
159+
['activation_cross_attn_q_length', ['fsdp', 'tensor']],
160+
['activation_length', 'fsdp'],
161+
['activation_heads', 'tensor'],
162+
['mlp','tensor'],
163+
['embed','fsdp'],
164+
['heads', 'tensor'],
165+
['norm', 'tensor'],
166+
['conv_batch', ['data','fsdp']],
167+
['out_channels', 'tensor'],
168+
['conv_out', 'fsdp'],
169+
]
170+
data_sharding: [['data', 'fsdp', 'tensor']]
171+
172+
# One axis for each parallelism type may hold a placeholder (-1)
173+
# value to auto-shard based on available slices and devices.
174+
# By default, product of the DCN axes should equal number of slices
175+
# and product of the ICI axes should equal number of devices per slice.
176+
dcn_data_parallelism: 1 # recommended DCN axis to be auto-sharded
177+
dcn_fsdp_parallelism: -1
178+
dcn_tensor_parallelism: 1
179+
ici_data_parallelism: 1
180+
ici_fsdp_parallelism: -1 # recommended ICI axis to be auto-sharded
181+
ici_tensor_parallelism: 1
182+
183+
allow_split_physical_axes: True
184+
185+
# Dataset
186+
# Replace with dataset path or train_data_dir. One has to be set.
187+
dataset_name: 'diffusers/pokemon-gpt4-captions'
188+
train_split: 'train'
189+
dataset_type: 'tfrecord'
190+
cache_latents_text_encoder_outputs: True
191+
# cache_latents_text_encoder_outputs only apply to dataset_type="tf",
192+
# only apply to small dataset that fits in memory
193+
# prepare image latents and text encoder outputs
194+
# Reduce memory consumption and reduce step time during training
195+
# transformed dataset is saved at dataset_save_location
196+
dataset_save_location: ''
197+
load_tfrecord_cached: True
198+
train_data_dir: ''
199+
dataset_config_name: ''
200+
jax_cache_dir: ''
201+
hf_data_dir: ''
202+
hf_train_files: ''
203+
hf_access_token: ''
204+
image_column: 'image'
205+
caption_column: 'text'
206+
resolution: 1024
207+
center_crop: False
208+
random_flip: False
209+
# If cache_latents_text_encoder_outputs is True
210+
# the num_proc is set to 1
211+
tokenize_captions_num_proc: 4
212+
transform_images_num_proc: 4
213+
reuse_example_batch: False
214+
enable_data_shuffling: True
215+
216+
# Defines the type of gradient checkpoint to enable.
217+
# NONE - means no gradient checkpoint
218+
# FULL - means full gradient checkpoint, whenever possible (minimum memory usage)
219+
# MATMUL_WITHOUT_BATCH - means gradient checkpoint for every linear/matmul operation,
220+
# except for ones that involve batch dimension - that means that all attention and projection
221+
# layers will have gradient checkpoint, but not the backward with respect to the parameters.
222+
# OFFLOAD_MATMUL_WITHOUT_BATCH - same as MATMUL_WITHOUT_BATCH but offload instead of recomputing.
223+
# CUSTOM - set names to offload and save.
224+
remat_policy: "NONE"
225+
# For CUSTOM policy set below, current annotations are for: attn_output, query_proj, key_proj, value_proj
226+
# xq_out, xk_out, ffn_activation
227+
names_which_can_be_saved: []
228+
names_which_can_be_offloaded: []
229+
230+
# checkpoint every number of samples, -1 means don't checkpoint.
231+
checkpoint_every: -1
232+
checkpoint_dir: ""
233+
# enables one replica to read the ckpt then broadcast to the rest
234+
enable_single_replica_ckpt_restoring: False
235+
236+
# Training loop
237+
learning_rate: 1.e-5
238+
scale_lr: False
239+
max_train_samples: -1
240+
# max_train_steps takes priority over num_train_epochs.
241+
max_train_steps: 1500
242+
num_train_epochs: 1
243+
seed: 0
244+
output_dir: 'sdxl-model-finetuned'
245+
per_device_batch_size: 1.0
246+
# If global_batch_size % jax.device_count is not 0, use FSDP sharding.
247+
global_batch_size: 0
248+
249+
# For creating tfrecords from dataset
250+
tfrecords_dir: ''
251+
no_records_per_shard: 0
252+
enable_eval_timesteps: False
253+
timesteps_list: [125, 250, 375, 500, 625, 750, 875]
254+
num_eval_samples: 420
255+
256+
warmup_steps_fraction: 0.1
257+
learning_rate_schedule_steps: -1 # By default the length of the schedule is set to the number of steps.
258+
save_optimizer: False
259+
260+
# However you may choose a longer schedule (learning_rate_schedule_steps > steps), in which case the training will end before
261+
# dropping fully down. Or you may choose a shorter schedule, where the unspecified steps will have a learning rate of 0.
262+
263+
# AdamW optimizer parameters
264+
adam_b1: 0.9 # Exponential decay rate to track the first moment of past gradients.
265+
adam_b2: 0.999 # Exponential decay rate to track the second moment of past gradients.
266+
adam_eps: 1.e-8 # A small constant applied to denominator outside of the square root.
267+
adam_weight_decay: 0 # AdamW Weight decay
268+
max_grad_norm: 1.0
269+
270+
enable_profiler: False
271+
# Skip first n steps for profiling, to omit things like compilation and to give
272+
# the iteration time a chance to stabilize.
273+
skip_first_n_steps_for_profiler: 5
274+
profiler_steps: 10
275+
276+
# Enable JAX named scopes for detailed profiling and debugging
277+
# When enabled, adds named scopes around key operations in transformer and attention layers
278+
enable_jax_named_scopes: False
279+
280+
# Generation parameters
281+
prompt: "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
282+
prompt_2: "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
283+
negative_prompt: "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
284+
do_classifier_free_guidance: True
285+
height: 720
286+
width: 1280
287+
num_frames: 81
288+
guidance_scale: 5.0
289+
flow_shift: 3.0
290+
291+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
292+
guidance_rescale: 0.0
293+
num_inference_steps: 30
294+
fps: 16
295+
save_final_checkpoint: False
296+
297+
# SDXL Lightning parameters
298+
lightning_from_pt: True
299+
# Empty or "ByteDance/SDXL-Lightning" to enable lightning.
300+
lightning_repo: ""
301+
# Empty or "sdxl_lightning_4step_unet.safetensors" to enable lightning.
302+
lightning_ckpt: ""
303+
304+
# LoRA parameters
305+
lora_rank: 64
306+
# Values are lists to support multiple LoRA loading during inference in the future.
307+
lora_config: {
308+
lora_model_name_or_path: ["lightx2v/Wan2.1-Distill-Loras"],
309+
weight_name: ["wan2.1_t2v_14b_lora_rank64_lightx2v_4step.safetensors"],
310+
adapter_name: ["wan21-distill-lora"],
311+
scale: [1.0],
312+
from_pt: []
313+
}
314+
# Ex with values:
315+
# lora_config : {
316+
# lora_model_name_or_path: ["ByteDance/Hyper-SD"],
317+
# weight_name: ["Hyper-SDXL-2steps-lora.safetensors"],
318+
# adapter_name: ["hyper-sdxl"],
319+
# scale: [0.7],
320+
# from_pt: [True]
321+
# }
322+
323+
enable_mllog: False
324+
325+
#controlnet
326+
controlnet_model_name_or_path: 'diffusers/controlnet-canny-sdxl-1.0'
327+
controlnet_from_pt: True
328+
controlnet_conditioning_scale: 0.5
329+
controlnet_image: 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Google_%22G%22_logo.svg/1024px-Google_%22G%22_logo.svg.png'
330+
quantization: ''
331+
# Shard the range finding operation for quantization. By default this is set to number of slices.
332+
quantization_local_shard_count: -1
333+
compile_topology_num_slices: -1 # Number of target slices, set to a positive integer.
334+
use_qwix_quantization: False # Whether to use qwix for quantization. If set to True, the transformer of WAN will be quantized using qwix.
335+
# Quantization calibration method used for weights, activations and bwd. Supported methods can be found in https://github.com/google/qwix/blob/dc2a0770351c740e5ab3cce7c0efe9f7beacce9e/qwix/qconfig.py#L70-L80
336+
weight_quantization_calibration_method: "absmax"
337+
act_quantization_calibration_method: "absmax"
338+
bwd_quantization_calibration_method: "absmax"
339+
qwix_module_path: ".*"
340+
341+
# Eval model on per eval_every steps. -1 means don't eval.
342+
eval_every: -1
343+
eval_data_dir: ""
344+
enable_generate_video_for_eval: False # This will increase the used TPU memory.
345+
eval_max_number_of_samples_in_bucket: 60 # The number of samples per bucket for evaluation. This is calculated by num_eval_samples / len(timesteps_list).
346+
347+
enable_ssim: False

0 commit comments

Comments
 (0)