(
model: nn.Module,
ckpts_folder: Union[str, os.PathLike],
)
| 15 | |
| 16 | |
| 17 | def mem_efficient_load_checkpoint( |
| 18 | model: nn.Module, |
| 19 | ckpts_folder: Union[str, os.PathLike], |
| 20 | ): |
| 21 | checkpoint_files = [ |
| 22 | ckpts_folder + "/" + f for f in os.listdir(ckpts_folder) if f.endswith(".pt") |
| 23 | ] |
| 24 | |
| 25 | # Check if the ckpts match the model |
| 26 | model_keys = sorted((list(model.state_dict().keys()))) |
| 27 | suffix = r"\.pt$" |
| 28 | ckpt_keys = sorted( |
| 29 | [re.sub(suffix, "", f) for f in os.listdir(ckpts_folder) if f.endswith(".pt")] |
| 30 | ) |
| 31 | assert len(model_keys) == len( |
| 32 | ckpt_keys |
| 33 | ), f"The number of checkpoint files do not match the model. \n Model has {len(model_keys)} keys, while finding {len(ckpt_keys)} checkpoint files in the folder." |
| 34 | for key1, key2 in zip(model_keys, ckpt_keys): |
| 35 | assert ( |
| 36 | key1 == key2 |
| 37 | ), f"The checkpoint files do not match the model. \nmodel key {key1} != checkpoint key {key2}" |
| 38 | |
| 39 | with tqdm(total=len(checkpoint_files)) as pbar: |
| 40 | pbar.set_description("Loading checkpoint shards") |
| 41 | for checkpoint_file in checkpoint_files: |
| 42 | checkpoint = torch.load(checkpoint_file, map_location=torch.device("cpu")) |
| 43 | model.load_state_dict(checkpoint, strict=False) |
| 44 | # Force Python to clean up. |
| 45 | del checkpoint |
| 46 | gc.collect() |
| 47 | pbar.update(1) |
| 48 | return model |
| 49 | |
| 50 | |
| 51 | def load_awq_model(model, checkpoint, w_bit, group_size, device): |
no test coverage detected