|
| 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 | + |
| 16 | +import json |
| 17 | +from typing import Optional, Tuple |
| 18 | +import jax |
| 19 | +from jax.sharding import Mesh, NamedSharding, PartitionSpec as P |
| 20 | +from maxdiffusion.checkpointing.wan_checkpointer import WanCheckpointer |
| 21 | +import numpy as np |
| 22 | +import orbax.checkpoint as ocp |
| 23 | +from .. import max_logging |
| 24 | +from ..pipelines.wan.wan_vace_pipeline_2_1 import VaceWanPipeline2_1 |
| 25 | + |
| 26 | + |
| 27 | +class WanVaceCheckpointer2_1(WanCheckpointer): |
| 28 | + |
| 29 | + def load_wan_configs_from_orbax(self, step: Optional[int]) -> Tuple[Optional[dict], Optional[int]]: |
| 30 | + if step is None: |
| 31 | + step = self.checkpoint_manager.latest_step() |
| 32 | + max_logging.log(f"Latest WAN checkpoint step: {step}") |
| 33 | + if step is None: |
| 34 | + max_logging.log("No WAN checkpoint found.") |
| 35 | + return None, None |
| 36 | + max_logging.log(f"Loading WAN checkpoint from step {step}") |
| 37 | + |
| 38 | + cpu_devices = np.array(jax.devices(backend="cpu")) |
| 39 | + mesh = Mesh(cpu_devices, axis_names=("data",)) |
| 40 | + replicated_sharding = NamedSharding(mesh, P()) |
| 41 | + |
| 42 | + metadatas = self.checkpoint_manager.item_metadata(step) |
| 43 | + state = metadatas.wan_state |
| 44 | + |
| 45 | + def add_sharding_to_struct(leaf_struct, sharding): |
| 46 | + struct = ocp.utils.to_shape_dtype_struct(leaf_struct) |
| 47 | + if hasattr(struct, "shape") and hasattr(struct, "dtype"): |
| 48 | + return jax.ShapeDtypeStruct(shape=struct.shape, dtype=struct.dtype, sharding=sharding) |
| 49 | + return struct |
| 50 | + |
| 51 | + target_shardings = jax.tree_util.tree_map(lambda x: replicated_sharding, state) |
| 52 | + |
| 53 | + with mesh: |
| 54 | + abstract_train_state_with_sharding = jax.tree_util.tree_map(add_sharding_to_struct, state, target_shardings) |
| 55 | + |
| 56 | + max_logging.log("Restoring WAN checkpoint") |
| 57 | + restored_checkpoint = self.checkpoint_manager.restore( |
| 58 | + step=step, |
| 59 | + args=ocp.args.Composite( |
| 60 | + wan_config=ocp.args.JsonRestore(), |
| 61 | + wan_state=ocp.args.StandardRestore(abstract_train_state_with_sharding), |
| 62 | + ), |
| 63 | + ) |
| 64 | + max_logging.log(f"restored checkpoint {restored_checkpoint.keys()}") |
| 65 | + max_logging.log(f"restored checkpoint wan_state {restored_checkpoint.wan_state.keys()}") |
| 66 | + max_logging.log(f"optimizer found in checkpoint {'opt_state' in restored_checkpoint.wan_state.keys()}") |
| 67 | + max_logging.log(f"optimizer state saved in attribute self.opt_state {self.opt_state}") |
| 68 | + return restored_checkpoint, step |
| 69 | + |
| 70 | + def load_diffusers_checkpoint(self): |
| 71 | + pipeline = VaceWanPipeline2_1.from_pretrained(self.config) |
| 72 | + return pipeline |
| 73 | + |
| 74 | + def load_checkpoint(self, step=None) -> Tuple[VaceWanPipeline2_1, Optional[dict], Optional[int]]: |
| 75 | + restored_checkpoint, step = self.load_wan_configs_from_orbax(step) |
| 76 | + opt_state = None |
| 77 | + if restored_checkpoint: |
| 78 | + max_logging.log("Loading WAN pipeline from checkpoint") |
| 79 | + pipeline = VaceWanPipeline2_1.from_checkpoint(self.config, restored_checkpoint) |
| 80 | + if "opt_state" in restored_checkpoint.wan_state.keys(): |
| 81 | + opt_state = restored_checkpoint.wan_state["opt_state"] |
| 82 | + else: |
| 83 | + max_logging.log("No checkpoint found, loading default pipeline.") |
| 84 | + pipeline = self.load_diffusers_checkpoint() |
| 85 | + |
| 86 | + return pipeline, opt_state, step |
| 87 | + |
| 88 | + def save_checkpoint(self, train_step, pipeline: VaceWanPipeline2_1, train_states: dict): |
| 89 | + """Saves the training state and model configurations.""" |
| 90 | + |
| 91 | + def config_to_json(model_or_config): |
| 92 | + return json.loads(model_or_config.to_json_string()) |
| 93 | + |
| 94 | + max_logging.log(f"Saving checkpoint for step {train_step}") |
| 95 | + |
| 96 | + # Save the checkpoint |
| 97 | + self.checkpoint_manager.save( |
| 98 | + train_step, |
| 99 | + args=ocp.args.Composite( |
| 100 | + wan_config=ocp.args.JsonSave(config_to_json(pipeline.transformer)), |
| 101 | + wan_state=ocp.args.StandardSave(train_states), |
| 102 | + ), |
| 103 | + ) |
| 104 | + |
| 105 | + max_logging.log(f"Checkpoint for step {train_step} is saved.") |
0 commit comments