-
Notifications
You must be signed in to change notification settings - Fork 74
feat: add pretrained orbax cache for fast WAN inference loads #406
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
csgoogle
wants to merge
1
commit into
main
Choose a base branch
from
wan-orbax-checkpoint-cache
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -20,7 +20,13 @@ | |
| from ..pipelines.wan.wan_pipeline_i2v_2p2 import WanPipelineI2V_2_2 | ||
| from .. import max_logging | ||
| import orbax.checkpoint as ocp | ||
| from maxdiffusion.checkpointing.checkpointing_utils import add_sharding_to_struct, get_cpu_mesh_and_sharding | ||
| from flax import nnx | ||
| from maxdiffusion.checkpointing.checkpointing_utils import ( | ||
| add_sharding_to_struct, | ||
| get_cpu_mesh_and_sharding, | ||
| create_orbax_checkpoint_manager, | ||
| WAN_CHECKPOINT, | ||
| ) | ||
| from maxdiffusion.checkpointing.wan_checkpointer import WanCheckpointer | ||
|
|
||
|
|
||
|
|
@@ -83,20 +89,100 @@ def load_diffusers_checkpoint(self): | |
| pipeline = WanPipelineI2V_2_2.from_pretrained(self.config) | ||
| return pipeline | ||
|
|
||
| def _get_pretrained_orbax_dir(self) -> str: | ||
| return getattr(self.config, "pretrained_orbax_dir", "") | ||
|
Comment on lines
+92
to
+93
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same as above |
||
|
|
||
| def save_pretrained_checkpoint(self, pretrained_dir: str, pipeline: WanPipelineI2V_2_2): | ||
| """Save pretrained weights (no optimizer state) to orbax for fast subsequent loads.""" | ||
| max_logging.log(f"Saving pretrained WAN 2.2 I2V weights to orbax at {pretrained_dir}") | ||
| pretrained_mgr = create_orbax_checkpoint_manager( | ||
| pretrained_dir, | ||
| enable_checkpointing=True, | ||
| save_interval_steps=1, | ||
| checkpoint_type=WAN_CHECKPOINT, | ||
| use_async=False, | ||
| ) | ||
| _, low_state, _ = nnx.split(pipeline.low_noise_transformer, nnx.Param, ...) | ||
| _, high_state, _ = nnx.split(pipeline.high_noise_transformer, nnx.Param, ...) | ||
| low_params = low_state.to_pure_dict() | ||
| high_params = high_state.to_pure_dict() | ||
| wan_config = json.loads(pipeline.low_noise_transformer.to_json_string()) | ||
| pretrained_mgr.save( | ||
| 0, | ||
| args=ocp.args.Composite( | ||
| wan_config=ocp.args.JsonSave(wan_config), | ||
| low_noise_transformer_state=ocp.args.StandardSave(low_params), | ||
| high_noise_transformer_state=ocp.args.StandardSave(high_params), | ||
| ), | ||
| ) | ||
| pretrained_mgr.wait_until_finished() | ||
| max_logging.log(f"Pretrained weights saved to {pretrained_dir}") | ||
|
|
||
| def load_pretrained_from_orbax(self, pretrained_dir: str) -> Tuple[Optional[object], Optional[int]]: | ||
| """Load pretrained weights from orbax cache if available.""" | ||
| try: | ||
| pretrained_mgr = create_orbax_checkpoint_manager( | ||
| pretrained_dir, | ||
| enable_checkpointing=True, | ||
| save_interval_steps=1, | ||
| checkpoint_type=WAN_CHECKPOINT, | ||
| use_async=False, | ||
| ) | ||
| step = pretrained_mgr.latest_step() | ||
| if step is None: | ||
| max_logging.log(f"No pretrained orbax checkpoint found in {pretrained_dir}") | ||
| return None, None | ||
| max_logging.log(f"Found pretrained orbax checkpoint (step {step}) in {pretrained_dir}") | ||
| mesh, replicated_sharding = get_cpu_mesh_and_sharding() | ||
| metadatas = pretrained_mgr.item_metadata(step) | ||
| low_meta = metadatas.low_noise_transformer_state | ||
| high_meta = metadatas.high_noise_transformer_state | ||
| target_shardings_low = jax.tree_util.tree_map(lambda x: replicated_sharding, low_meta) | ||
| target_shardings_high = jax.tree_util.tree_map(lambda x: replicated_sharding, high_meta) | ||
| with mesh: | ||
| abstract_low = jax.tree_util.tree_map(add_sharding_to_struct, low_meta, target_shardings_low) | ||
| abstract_high = jax.tree_util.tree_map(add_sharding_to_struct, high_meta, target_shardings_high) | ||
| max_logging.log("Restoring pretrained WAN 2.2 I2V weights from orbax") | ||
| restored = pretrained_mgr.restore( | ||
| step, | ||
| args=ocp.args.Composite( | ||
| wan_config=ocp.args.JsonRestore(), | ||
| low_noise_transformer_state=ocp.args.StandardRestore(abstract_low), | ||
| high_noise_transformer_state=ocp.args.StandardRestore(abstract_high), | ||
| ), | ||
| ) | ||
| return restored, step | ||
| except Exception as e: # pylint: disable=broad-except | ||
| max_logging.log(f"Failed to load pretrained orbax checkpoint from {pretrained_dir}: {e}") | ||
| return None, None | ||
|
|
||
| def load_checkpoint(self, step=None) -> Tuple[WanPipelineI2V_2_2, Optional[dict], Optional[int]]: | ||
| pretrained_dir = self._get_pretrained_orbax_dir() | ||
|
|
||
| # 1. Fast path: load from pretrained orbax cache (skips diffusers entirely). | ||
| if pretrained_dir: | ||
| restored, loaded_step = self.load_pretrained_from_orbax(pretrained_dir) | ||
| if restored is not None: | ||
| max_logging.log("Loading WAN 2.2 I2V pipeline from pretrained orbax checkpoint") | ||
| pipeline = WanPipelineI2V_2_2.from_checkpoint(self.config, restored) | ||
| return pipeline, None, loaded_step | ||
|
|
||
| # 2. Try training checkpoint from checkpoint_dir. | ||
| restored_checkpoint, step = self.load_wan_configs_from_orbax(step) | ||
| opt_state = None | ||
| if restored_checkpoint: | ||
| max_logging.log("Loading WAN pipeline from checkpoint") | ||
| max_logging.log("Loading WAN pipeline from training checkpoint") | ||
| pipeline = WanPipelineI2V_2_2.from_checkpoint(self.config, restored_checkpoint) | ||
| # Check for optimizer state in either transformer | ||
| if "opt_state" in restored_checkpoint.low_noise_transformer_state.keys(): | ||
| opt_state = restored_checkpoint.low_noise_transformer_state["opt_state"] | ||
| elif "opt_state" in restored_checkpoint.high_noise_transformer_state.keys(): | ||
| opt_state = restored_checkpoint.high_noise_transformer_state["opt_state"] | ||
| else: | ||
| max_logging.log("No checkpoint found, loading default pipeline.") | ||
| # 3. Slow path: load from diffusers, then cache to orbax for next time. | ||
| max_logging.log("No checkpoint found, loading pipeline from diffusers.") | ||
| pipeline = self.load_diffusers_checkpoint() | ||
| if pretrained_dir: | ||
| self.save_pretrained_checkpoint(pretrained_dir, pipeline) | ||
|
|
||
| return pipeline, opt_state, step | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we need this function? We could just directly use
getattr(self.config, "pretrained_orbax_dir", "")as it is only needed in one place. Also should the default value beNoneinstead of""