model load parameters Args: path (str): checkpoint path model (nn.Module): model instance strict (bool, optional): strictly load. Defaults to True. Returns: nn.Module: _description_
(
path: str, model: nn.Module, strict: bool = True, device: str = None
)
| 87 | |
| 88 | |
| 89 | def model_load( |
| 90 | path: str, model: nn.Module, strict: bool = True, device: str = None |
| 91 | ) -> nn.Module: |
| 92 | """model load parameters |
| 93 | |
| 94 | Args: |
| 95 | path (str): checkpoint path |
| 96 | model (nn.Module): model instance |
| 97 | strict (bool, optional): strictly load. Defaults to True. |
| 98 | |
| 99 | Returns: |
| 100 | nn.Module: _description_ |
| 101 | """ |
| 102 | if not exist(device): |
| 103 | device = next(model.parameters()).device |
| 104 | params = torch.load(path, map_location=device) |
| 105 | try: |
| 106 | model.load_state_dict(params, strict=strict) |
| 107 | except Exception: |
| 108 | try: |
| 109 | odict = OrderedDict() |
| 110 | # remove module. |
| 111 | for k, v in params.items(): |
| 112 | k.replace("module.", "") |
| 113 | odict[k] = v |
| 114 | |
| 115 | model.load_state_dict(odict, strict=strict) |
| 116 | except Exception: |
| 117 | if not strict: |
| 118 | model = _regardless_keys_unmatch_shape_unmatch(model, params) |
| 119 | else: |
| 120 | raise RuntimeError("strict is True, but model load failed") |
| 121 | |
| 122 | return model |
| 123 | |
| 124 | |
| 125 | def _regardless_keys_unmatch_shape_unmatch(model, state_dict): |