forked from Lightning-AI/lit-llama
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Save checkpoint in train.py (Lightning-AI#89)
- Loading branch information
Showing
2 changed files
with
30 additions
and
5 deletions.
There are no files selected for viewing
This file contains 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,24 @@ | ||
"""Utility functions for training and inference.""" | ||
|
||
import torch | ||
from lightning.fabric.strategies import FSDPStrategy | ||
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP | ||
from torch.distributed.fsdp import StateDictType, FullStateDictConfig | ||
|
||
|
||
def save_model_checkpoint(fabric, model, file_path): | ||
"""Handles boilerplate logic for retrieving and saving the state_dict. | ||
This will be upstreamed to Fabric soon. | ||
""" | ||
|
||
if isinstance(fabric.strategy, FSDPStrategy): | ||
save_policy = FullStateDictConfig(offload_to_cpu=True, rank0_only=True) | ||
with FSDP.state_dict_type(model, StateDictType.FULL_STATE_DICT, save_policy): | ||
state_dict = model._forward_module.state_dict() | ||
else: | ||
state_dict = model.state_dict() | ||
|
||
if fabric.global_rank == 0: | ||
torch.save(state_dict, file_path) | ||
fabric.barrier() |
This file contains 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