| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| from dataclasses import dataclass |
| from pathlib import Path |
|
|
| import torch |
| from omegaconf import OmegaConf |
|
|
| from nemo.core.config import hydra_runner |
| from nemo.utils.model_utils import import_class_by_path |
|
|
|
|
| @dataclass |
| class HfExportConfig: |
| |
| class_path: str |
|
|
| |
| ckpt_path: str |
|
|
| |
| ckpt_config: str |
|
|
| |
| output_dir: str |
|
|
| |
| dtype: str = "bfloat16" |
|
|
|
|
| def load_checkpoint(model: torch.nn.Module, checkpoint_path: str): |
| if Path(checkpoint_path).is_dir(): |
| from torch.distributed.checkpoint import load |
|
|
| state_dict = {"state_dict": model.state_dict()} |
| load(state_dict, checkpoint_id=checkpoint_path) |
| model.load_state_dict(state_dict["state_dict"]) |
| else: |
| ckpt_data = torch.load(checkpoint_path, map_location="cpu") |
| model.load_state_dict(ckpt_data["state_dict"]) |
|
|
|
|
| @hydra_runner(config_name="HfExportConfig", schema=HfExportConfig) |
| def main(cfg: HfExportConfig): |
| """ |
| Read PyTorch Lightning checkpoint and export the model to HuggingFace Hub format. |
| The resulting model can be then initialized via ModelClass.from_pretrained(path). |
| |
| Also supports distributed checkpoints for models trained with FSDP2/TP. |
| """ |
| model_cfg = OmegaConf.to_container(OmegaConf.load(cfg.ckpt_config).model, resolve=True) |
| model_cfg["torch_dtype"] = cfg.dtype |
| cls = import_class_by_path(cfg.class_path) |
| model = cls(model_cfg) |
| load_checkpoint(model, cfg.ckpt_path) |
| model = model.to(getattr(torch, cfg.dtype)) |
| model.save_pretrained(cfg.output_dir) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|