1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
#
def load_pretrained(
model: torch.nn.Module,
pretrained_params: dict = None,
strict: bool = False,
prefix: list = None,
use_flash_attn = True,
verbose: bool = True,
) -> torch.nn.Module:
# 修改特定参数的key name
if not use_flash_attn:
pretrained_params = {
k.replace("Wqkv.", "in_proj_"): v for k, v in pretrained_params.items()
}
# 只加载特定keys的参数
if prefix is not None and len(prefix) > 0:
if isinstance(prefix, str):
prefix = [prefix]
pretrained_params = {
k: v
for k, v in pretrained_params.items()
if any(k.startswith(p) for p in prefix)
}
model_dict = model.state_dict()
# 严格加载:全部参数需要匹配
if strict:
if verbose:
for k, v in pretrained_params.items():
print(f"Loading parameter {k} with shape {v.shape}")
model_dict.update(pretrained_params)
model.load_state_dict(model_dict)
# 部分加载:只加载部分能够匹配的参数(key name以及 value shape)
else:
if verbose:
for k, v in pretrained_params.items():
if k in model_dict and v.shape == model_dict[k].shape:
print(f"Loading parameter {k} with shape {v.shape}")
pretrained_params = {
k: v
for k, v in pretrained_params.items()
if k in model_dict and v.shape == model_dict[k].shape
}
model_dict.update(pretrained_params)
model.load_state_dict(model_dict)
return model
|