-
Notifications
You must be signed in to change notification settings - Fork 567
feat(archon): add DCP-based HF checkpoint save/load with MoE expert support #849
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
Merged
Merged
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,179 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| import shutil | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| import torch | ||
| import torch.distributed as dist | ||
| import torch.distributed.checkpoint as dcp | ||
| from torch.distributed.checkpoint.state_dict import ( | ||
| StateDictOptions, | ||
| get_model_state_dict, | ||
| set_model_state_dict, | ||
| ) | ||
|
|
||
| from areal.utils.fsdp.checkpoint import DCPState | ||
|
|
||
| if TYPE_CHECKING: | ||
| from transformers import AutoProcessor, PreTrainedTokenizerFast | ||
|
|
||
| from areal.experimental.engine.archon_engine import ArchonEngine | ||
|
|
||
|
|
||
| def save_model_to_hf( | ||
| engine: ArchonEngine, | ||
| path: str, | ||
| tokenizer: PreTrainedTokenizerFast | None, | ||
| processor: AutoProcessor | None = None, | ||
| ) -> None: | ||
| """Save model in HuggingFace format using DCP infrastructure.""" | ||
| from torch.distributed.checkpoint import HuggingFaceStorageWriter | ||
|
|
||
| if engine.model is None: | ||
| raise RuntimeError("Model not initialized") | ||
| if engine.state_dict_adapter is None: | ||
| raise RuntimeError("state_dict_adapter is required for HF format") | ||
|
|
||
| engine.logger.info(f"Saving HF checkpoint to {path}") | ||
| os.makedirs(path, exist_ok=True) | ||
|
|
||
| # Get distributed state dict | ||
| options = StateDictOptions(full_state_dict=False, cpu_offload=True) | ||
| state_dict = get_model_state_dict(engine.model, options=options) | ||
|
|
||
| # Convert to HF format using adapter | ||
| hf_state_dict = engine.state_dict_adapter.to_hf(state_dict) | ||
|
|
||
| fqn_to_index_mapping = engine.state_dict_adapter.fqn_to_index_mapping | ||
|
|
||
| # NOTE: HuggingFaceStorageWriter always creates a sharded/ subdirectory when | ||
| # save_distributed=True. With enable_consolidation=True, it saves shards to | ||
| # path/sharded/, then consolidates to path/. The sharded/ directory is NOT | ||
| # automatically cleaned up by PyTorch, so we must remove it manually. | ||
| sharded_dir = os.path.join(path, "sharded") | ||
|
|
||
| if fqn_to_index_mapping: | ||
| # Multi-file output: save to sharded/, then consolidate with all ranks | ||
| from torch.distributed.checkpoint._consolidate_hf_safetensors import ( | ||
| consolidate_safetensors_files_on_every_rank, | ||
| ) | ||
|
|
||
| hf_writer = HuggingFaceStorageWriter( | ||
| path=sharded_dir, | ||
| save_distributed=True, | ||
| fqn_to_index_mapping=fqn_to_index_mapping, | ||
| enable_consolidation=False, | ||
| ) | ||
| dcp.save(hf_state_dict, storage_writer=hf_writer) | ||
|
|
||
| # NOTE: consolidate_safetensors_files_on_every_rank() has internal barrier | ||
| consolidate_safetensors_files_on_every_rank( | ||
| input_dir=sharded_dir, | ||
| output_dir=path, | ||
| fqn_to_index_mapping=fqn_to_index_mapping, | ||
| num_threads=8, | ||
| ) | ||
| else: | ||
| # Single-file output: auto consolidation | ||
| hf_writer = HuggingFaceStorageWriter( | ||
| path=path, | ||
| save_distributed=True, | ||
| enable_consolidation=True, | ||
| ) | ||
| dcp.save(hf_state_dict, storage_writer=hf_writer) | ||
|
|
||
| # Clean up sharded/ directory after consolidation | ||
| if dist.get_rank() == 0 and os.path.exists(sharded_dir): | ||
| shutil.rmtree(sharded_dir) | ||
|
|
||
| dist.barrier(group=engine.cpu_group) | ||
|
|
||
| if dist.get_rank() == 0: | ||
| engine.model_config.save_pretrained(path) | ||
| if tokenizer is not None: | ||
| tokenizer.save_pretrained(path) | ||
| if processor is not None: | ||
| processor.save_pretrained(path) | ||
| dist.barrier(group=engine.cpu_group) | ||
|
|
||
|
|
||
| def load_model_from_hf(engine: ArchonEngine, path: str) -> None: | ||
| """Load model from HuggingFace format using DCP infrastructure.""" | ||
| if engine.model is None: | ||
| raise RuntimeError("Model not initialized") | ||
| if engine.state_dict_adapter is None: | ||
| raise RuntimeError("state_dict_adapter is required for HF format") | ||
|
|
||
| engine.logger.info(f"Loading HF checkpoint from {path}") | ||
|
|
||
| # Get model state dict structure (distributed) | ||
| options = StateDictOptions(full_state_dict=False, cpu_offload=True) | ||
| state_dict = get_model_state_dict(engine.model, options=options) | ||
|
|
||
| # Convert to HF format to match checkpoint keys | ||
| hf_state_dict = engine.state_dict_adapter.to_hf(state_dict) | ||
|
|
||
| # Load using DCP with HuggingFaceStorageReader | ||
| hf_reader = engine.state_dict_adapter.get_hf_storage_reader(path) | ||
| dcp.load(hf_state_dict, storage_reader=hf_reader) | ||
|
|
||
| # Convert back to Archon format | ||
| archon_state_dict = engine.state_dict_adapter.from_hf(hf_state_dict) | ||
|
|
||
| # Load into FSDP model (same as DCPState.load_state_dict) | ||
| set_model_state_dict( | ||
| engine.model, | ||
| model_state_dict=archon_state_dict, | ||
| options=StateDictOptions(strict=False), | ||
| ) | ||
|
|
||
| dist.barrier(group=engine.cpu_group) | ||
|
|
||
|
|
||
| def save_to_dcp(engine: ArchonEngine, path: str, with_optim: bool) -> None: | ||
| """Save model (and optionally optimizer) using DCP format.""" | ||
| if engine.model is None: | ||
| raise RuntimeError("Model not initialized") | ||
|
|
||
| os.makedirs(path, exist_ok=True) | ||
|
|
||
| dcp_state = DCPState(engine.model, engine.optimizer if with_optim else None) | ||
| state_dict = {"dcp": dcp_state} | ||
| dcp.save(state_dict, checkpoint_id=path) | ||
|
|
||
|
|
||
| def load_from_dcp(engine: ArchonEngine, path: str, with_optim: bool) -> None: | ||
| """Load model (and optionally optimizer) from DCP format.""" | ||
| if engine.model is None: | ||
| raise RuntimeError("Model not initialized") | ||
|
|
||
| dcp_state = DCPState(engine.model, engine.optimizer if with_optim else None) | ||
| state_dict = {"dcp": dcp_state} | ||
| dcp.load(state_dict=state_dict, checkpoint_id=path) | ||
|
|
||
|
|
||
| def save_optimizer_state(engine: ArchonEngine, path: str) -> None: | ||
| """Save optimizer state to disk (sharded by rank).""" | ||
| assert engine.optimizer is not None | ||
| assert dist.is_initialized() | ||
| rank = dist.get_rank() | ||
| shard_path = os.path.join( | ||
| path, f"optim_world_size_{engine.world_size}_rank_{rank}.pt" | ||
| ) | ||
| state_dict = engine.optimizer.state_dict() | ||
| torch.save(state_dict, shard_path) | ||
| dist.barrier(group=engine.cpu_group) | ||
|
|
||
|
|
||
| def load_optimizer_state(engine: ArchonEngine, path: str) -> None: | ||
| """Load optimizer state from disk (sharded by rank).""" | ||
| assert engine.optimizer is not None | ||
| assert dist.is_initialized() | ||
| rank = dist.get_rank() | ||
| shard_path = os.path.join( | ||
| path, f"optim_world_size_{engine.world_size}_rank_{rank}.pt" | ||
| ) | ||
| optimizer_state_dict = torch.load(shard_path, weights_only=False) | ||
| engine.optimizer.load_state_dict(optimizer_state_dict) | ||
| dist.barrier(group=engine.cpu_group) | ||
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.
What about the performance?
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.
Our benchmark on a 12.55 GB model across 8 GPUs shows that DCP provides a modest 1.10x speedup (11.18s vs 12.27s), but the real advantage is memory efficiency: DCP uses 23x less CPU memory (0.45 GB vs 10.52 GB). The baseline approach with
full_state_dict=Truegathers the entire model to each rank before saving, consuming ~10.5 GB extra CPU memory per rank—this becomes the bottleneck for larger models where OOM is inevitable. DCP keeps data sharded throughout the save process, using only ~1.57 GB per rank. The time breakdown reveals that DCP's get_state_dict is 7x faster (0.39s vs 2.72s) by avoiding all-gather communication, though the two-phase write (DCP save + consolidate) takes longer than single-rank sequential write. In summary, DCP's primary value is enabling checkpoint saves for large models that would otherwise OOM, with a secondary benefit of slightly better throughput at scale.Benchmarking: https://gist.github.com/rchardx/bc558b7bf7cab969e4075a71b17ed1a9