(cur_model, ckpt_base_dir, prefix_in_ckpt='model', force=True, strict=True)
| 176 | |
| 177 | |
| 178 | def load_ckpt(cur_model, ckpt_base_dir, prefix_in_ckpt='model', force=True, strict=True): |
| 179 | if os.path.isfile(ckpt_base_dir): |
| 180 | base_dir = os.path.dirname(ckpt_base_dir) |
| 181 | checkpoint_path = [ckpt_base_dir] |
| 182 | else: |
| 183 | base_dir = ckpt_base_dir |
| 184 | checkpoint_path = sorted(glob.glob(f'{base_dir}/model_ckpt_steps_*.ckpt'), key= |
| 185 | lambda x: int(re.findall(f'{base_dir}/model_ckpt_steps_(\d+).ckpt', x)[0])) |
| 186 | if len(checkpoint_path) > 0: |
| 187 | checkpoint_path = checkpoint_path[-1] |
| 188 | state_dict = torch.load(checkpoint_path, map_location="cpu")["state_dict"] |
| 189 | state_dict = {k[len(prefix_in_ckpt) + 1:]: v for k, v in state_dict.items() |
| 190 | if k.startswith(f'{prefix_in_ckpt}.')} |
| 191 | if not strict: |
| 192 | cur_model_state_dict = cur_model.state_dict() |
| 193 | unmatched_keys = [] |
| 194 | for key, param in state_dict.items(): |
| 195 | if key in cur_model_state_dict: |
| 196 | new_param = cur_model_state_dict[key] |
| 197 | if new_param.shape != param.shape: |
| 198 | unmatched_keys.append(key) |
| 199 | print("| Unmatched keys: ", key, new_param.shape, param.shape) |
| 200 | for key in unmatched_keys: |
| 201 | del state_dict[key] |
| 202 | cur_model.load_state_dict(state_dict, strict=strict) |
| 203 | print(f"| load '{prefix_in_ckpt}' from '{checkpoint_path}'.") |
| 204 | else: |
| 205 | e_msg = f"| ckpt not found in {base_dir}." |
| 206 | if force: |
| 207 | assert False, e_msg |
| 208 | else: |
| 209 | print(e_msg) |
| 210 | |
| 211 | |
| 212 | def remove_padding(x, padding_idx=0): |
nothing calls this directly
no outgoing calls
no test coverage detected