|
| 1 | +""" |
| 2 | +Copyright 2025 Google LLC |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +""" |
| 16 | + |
| 17 | +import json |
| 18 | +import jax |
| 19 | +import numpy as np |
| 20 | +from typing import Optional, Tuple |
| 21 | +from maxdiffusion.pipelines.ideogram.ideogram_pipeline import IdeogramPipeline |
| 22 | +from maxdiffusion import max_logging |
| 23 | +from maxdiffusion.checkpointing.checkpointing_utils import create_orbax_checkpoint_manager |
| 24 | +import orbax.checkpoint as ocp |
| 25 | +from etils import epath |
| 26 | + |
| 27 | +IDEOGRAM_CHECKPOINT = "IDEOGRAM_CHECKPOINT" |
| 28 | + |
| 29 | + |
| 30 | +class IdeogramCheckpointer: |
| 31 | + |
| 32 | + def __init__(self, config, checkpoint_type: str = IDEOGRAM_CHECKPOINT): |
| 33 | + self.config = config |
| 34 | + self.checkpoint_type = checkpoint_type |
| 35 | + self.opt_state = None |
| 36 | + |
| 37 | + self.checkpoint_manager: ocp.CheckpointManager = create_orbax_checkpoint_manager( |
| 38 | + getattr(self.config, "checkpoint_dir", ""), |
| 39 | + enable_checkpointing=True, |
| 40 | + save_interval_steps=1, |
| 41 | + checkpoint_type=checkpoint_type, |
| 42 | + dataset_type=getattr(config, "dataset_type", None), |
| 43 | + ) |
| 44 | + |
| 45 | + def load_ideogram_configs_from_orbax(self, step: Optional[int]) -> Tuple[Optional[dict], Optional[int]]: |
| 46 | + if self.checkpoint_manager is None: |
| 47 | + max_logging.log("No checkpoint manager configured, skipping Orbax load.") |
| 48 | + return None, None |
| 49 | + |
| 50 | + if step is None: |
| 51 | + step = self.checkpoint_manager.latest_step() |
| 52 | + max_logging.log(f"Latest Ideogram checkpoint step: {step}") |
| 53 | + if step is None: |
| 54 | + max_logging.log("No Ideogram checkpoint found.") |
| 55 | + return None, None |
| 56 | + max_logging.log(f"Loading Ideogram checkpoint from step {step}") |
| 57 | + metadatas = self.checkpoint_manager.item_metadata(step) |
| 58 | + transformer_metadata = metadatas.ideogram_state |
| 59 | + abstract_tree_structure_params = jax.tree_util.tree_map(ocp.utils.to_shape_dtype_struct, transformer_metadata) |
| 60 | + params_restore = ocp.args.PyTreeRestore( |
| 61 | + restore_args=jax.tree.map( |
| 62 | + lambda _: ocp.RestoreArgs(restore_type=np.ndarray), |
| 63 | + abstract_tree_structure_params, |
| 64 | + ) |
| 65 | + ) |
| 66 | + |
| 67 | + max_logging.log("Restoring Ideogram checkpoint") |
| 68 | + restored_checkpoint = self.checkpoint_manager.restore( |
| 69 | + directory=epath.Path(self.config.checkpoint_dir), |
| 70 | + step=step, |
| 71 | + args=ocp.args.Composite( |
| 72 | + ideogram_state=params_restore, |
| 73 | + ideogram_config=ocp.args.JsonRestore(), |
| 74 | + ), |
| 75 | + ) |
| 76 | + max_logging.log(f"restored checkpoint {restored_checkpoint.keys()}") |
| 77 | + max_logging.log(f"restored checkpoint ideogram_state {restored_checkpoint.ideogram_state.keys()}") |
| 78 | + max_logging.log(f"optimizer found in checkpoint {'opt_state' in restored_checkpoint.ideogram_state.keys()}") |
| 79 | + return restored_checkpoint, step |
| 80 | + |
| 81 | + def load_checkpoint( |
| 82 | + self, step=None, vae_only=False, load_transformer=True |
| 83 | + ) -> Tuple[IdeogramPipeline, Optional[dict], Optional[int]]: |
| 84 | + restored_checkpoint, step = self.load_ideogram_configs_from_orbax(step) |
| 85 | + opt_state = None |
| 86 | + |
| 87 | + if restored_checkpoint: |
| 88 | + max_logging.log("Loading Ideogram pipeline from checkpoint") |
| 89 | + pipeline = IdeogramPipeline.from_checkpoint(self.config, restored_checkpoint, vae_only, load_transformer) |
| 90 | + if "opt_state" in restored_checkpoint.ideogram_state.keys(): |
| 91 | + opt_state = restored_checkpoint.ideogram_state["opt_state"] |
| 92 | + else: |
| 93 | + max_logging.log("No checkpoint found, loading pipeline from pretrained hub") |
| 94 | + pipeline = IdeogramPipeline.from_pretrained(self.config, vae_only, load_transformer) |
| 95 | + |
| 96 | + return pipeline, opt_state, step |
| 97 | + |
| 98 | + def save_checkpoint(self, train_step, pipeline: IdeogramPipeline, train_states: dict): |
| 99 | + """Saves the training state and model configurations.""" |
| 100 | + |
| 101 | + def config_to_json(model_or_config): |
| 102 | + return json.loads(model_or_config.to_json_string()) |
| 103 | + |
| 104 | + max_logging.log(f"Saving checkpoint for step {train_step}") |
| 105 | + items = { |
| 106 | + "ideogram_config": ocp.args.JsonSave(config_to_json(pipeline.transformer)), |
| 107 | + } |
| 108 | + |
| 109 | + items["ideogram_state"] = ocp.args.PyTreeSave(train_states) |
| 110 | + |
| 111 | + # Save the checkpoint |
| 112 | + self.checkpoint_manager.save(train_step, args=ocp.args.Composite(**items)) |
| 113 | + max_logging.log(f"Checkpoint for step {train_step} saved.") |
0 commit comments