Load a model state and set it to the model. Args: init_param: : : : Examples:
(
path: str,
model: torch.nn.Module,
ignore_init_mismatch: bool = True,
map_location: str = "cpu",
oss_bucket=None,
scope_map=[],
excludes=None,
**kwargs,
)
| 12 | |
| 13 | |
| 14 | def load_pretrained_model( |
| 15 | path: str, |
| 16 | model: torch.nn.Module, |
| 17 | ignore_init_mismatch: bool = True, |
| 18 | map_location: str = "cpu", |
| 19 | oss_bucket=None, |
| 20 | scope_map=[], |
| 21 | excludes=None, |
| 22 | **kwargs, |
| 23 | ): |
| 24 | """Load a model state and set it to the model. |
| 25 | |
| 26 | Args: |
| 27 | init_param: <file_path>:<src_key>:<dst_key>:<exclude_Keys> |
| 28 | |
| 29 | Examples: |
| 30 | |
| 31 | """ |
| 32 | |
| 33 | obj = model |
| 34 | dst_state = obj.state_dict() |
| 35 | |
| 36 | logging.info(f"ckpt: {path}") |
| 37 | |
| 38 | if oss_bucket is None: |
| 39 | ori_state = torch.load(path, map_location=map_location) |
| 40 | else: |
| 41 | buffer = BytesIO(oss_bucket.get_object(path).read()) |
| 42 | ori_state = torch.load(buffer, map_location=map_location) |
| 43 | |
| 44 | src_state = copy.deepcopy(ori_state) |
| 45 | src_state = src_state["state_dict"] if "state_dict" in src_state else src_state |
| 46 | src_state = src_state["model_state_dict"] if "model_state_dict" in src_state else src_state |
| 47 | src_state = src_state["model"] if "model" in src_state else src_state |
| 48 | |
| 49 | if isinstance(scope_map, str): |
| 50 | scope_map = scope_map.split(",") |
| 51 | scope_map += ["module.", "None"] |
| 52 | logging.info(f"scope_map: {scope_map}") |
| 53 | |
| 54 | if excludes is not None: |
| 55 | if isinstance(excludes, str): |
| 56 | excludes = excludes.split(",") |
| 57 | |
| 58 | logging.info(f"excludes: {excludes}") |
| 59 | |
| 60 | for k in dst_state.keys(): |
| 61 | excludes_flag = False |
| 62 | if excludes is not None: |
| 63 | for k_ex in excludes: |
| 64 | if k.startswith(k_ex): |
| 65 | logging.info(f"key: {k} matching: {k_ex}, excluded") |
| 66 | excludes_flag = True |
| 67 | break |
| 68 | if excludes_flag: |
| 69 | continue |
| 70 | |
| 71 | k_src = k |
no test coverage detected
searching dependent graphs…