File size: 1,756 Bytes
11d8066
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reassemble a full text-classification state_dict from a ParaGen-Bench pool checkpoint and its base checkpoint.

Pool files (ckpt/text_classification/<arch>__<dataset>/<model_id>/collect_XXX.pth) omit the vocabulary token-embedding
matrix, which was frozen during collection and is therefore identical to the base model's. It is stored once, in the
base checkpoint zoo/<dataset>/<arch>/<model_id>.pth. Every pool file lists the omitted keys under "frozen_keys".

    from assemble import assemble
    sd = assemble("zoo/agnews/bertbase/bertbase_010.pth",
                  "ckpt/text_classification/bertbase__agnews/bertbase_010/collect_000.pth")
    model.load_state_dict(sd, strict=True)
"""
import torch


def assemble(base_ckpt_path, pool_ckpt_path, map_location="cpu"):
    """Return the full model state_dict: pool weights + the frozen keys copied from the base's model_state_dict."""
    pool = torch.load(pool_ckpt_path, map_location=map_location, weights_only=False)
    base = torch.load(base_ckpt_path, map_location=map_location, weights_only=False)
    sd = dict(pool["model_state_dict"])
    base_sd = base["model_state_dict"]
    for k in pool["frozen_keys"]:
        if k in sd:
            raise ValueError(f"frozen key {k!r} is unexpectedly present in the pool file")
        if k not in base_sd:
            raise KeyError(f"frozen key {k!r} not found in the base checkpoint {base_ckpt_path}")
        sd[k] = base_sd[k].to(torch.float32)
    return sd


if __name__ == "__main__":
    import sys
    if len(sys.argv) != 3:
        raise SystemExit("usage: python assemble.py <base_ckpt.pth> <collect_XXX.pth>")
    sd = assemble(sys.argv[1], sys.argv[2])
    print(f"{len(sd)} tensors, {sum(v.numel() for v in sd.values()):,} values")