File size: 1,921 Bytes
24baf68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Export a training checkpoint to the inference tail file (student tail + DWD head, safetensors).

    python scripts/export_checkpoint.py --ckpt checkpoints/<run>/ckpt_026000.pt --out dwd_tail.safetensors

By default the EMA weights are exported in bf16. --raw exports the raw (non-EMA) weights, --fp32 keeps fp32.
Optimizer, discriminator, RNG and config entries of the checkpoint are not exported.
"""

import argparse
import json
import os
import sys

try:
    from dwd_klein.export import export_checkpoint
except ImportError:  # running from a source checkout without installing the package
    sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src"))
    from dwd_klein.export import export_checkpoint


def main(argv=None) -> int:
    import torch

    ap = argparse.ArgumentParser(description="training checkpoint -> dwd_tail.safetensors")
    ap.add_argument("--ckpt", required=True, help="training checkpoint (.pt), a run directory (uses its 'latest'), or a 'latest' file")
    ap.add_argument("--out", default="dwd_tail.safetensors")
    ap.add_argument("--raw", action="store_true", help="export the raw weights instead of the EMA weights")
    ap.add_argument("--fp32", action="store_true", help="store fp32 tensors instead of bf16")
    a = ap.parse_args(argv)
    ckpt = a.ckpt
    if os.path.isdir(ckpt):
        with open(os.path.join(ckpt, "latest")) as fh:
            ckpt = os.path.join(ckpt, fh.read().strip())
    elif os.path.basename(ckpt) == "latest":
        with open(ckpt) as fh:
            ckpt = os.path.join(os.path.dirname(ckpt), fh.read().strip())
    meta = export_checkpoint(ckpt, a.out, use_ema=not a.raw, dtype=torch.float32 if a.fp32 else torch.bfloat16)
    print(f"wrote {a.out} ({os.path.getsize(a.out) / 1e6:.1f} MB)")
    print(json.dumps(meta, indent=1))
    return 0


if __name__ == "__main__":
    sys.exit(main())