File size: 2,275 Bytes
830e33a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
50
51
52
53
#!/usr/bin/env python3
"""Save the training-free looped LFM3 (default: window [8,11] x2, alpha=0.5) as a plain
HF checkpoint, so it loads with trust_remote_code and scores in lm-evaluation-harness.

    python save_loop_hf.py --base LiquidAI/LFM3-1.7B-Base --out ./LFM3-1.7B-loop-8-11
"""
import argparse, os, shutil, sys
import torch

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import tfl


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--base", default=os.environ.get("LFM3_BASE", "LiquidAI/LFM3-1.7B-Base"))
    ap.add_argument("--out", required=True)
    ap.add_argument("--window", default="8,11")
    ap.add_argument("--reps", type=int, default=2)
    ap.add_argument("--alpha", type=float, default=0.5)
    ap.add_argument("--device", default="cpu", help="cpu (default) or cuda")
    args = ap.parse_args()

    def load_here(path=None, dtype=torch.bfloat16):
        from transformers import AutoModelForCausalLM, AutoTokenizer
        tok = AutoTokenizer.from_pretrained(args.base, trust_remote_code=True)
        m = AutoModelForCausalLM.from_pretrained(
            args.base, trust_remote_code=True, dtype=dtype,
            attn_implementation="sdpa", device_map={"": args.device})
        return m, tok

    tfl.load = load_here
    a, b = [int(x) for x in args.window.split(",")]
    m, tok = tfl.build((a, b), reps=args.reps, alpha=args.alpha)
    print(f"layers {m.config.num_hidden_layers}  layer_types {len(m.config.layer_types)}")
    os.makedirs(args.out, exist_ok=True)
    m.save_pretrained(args.out, safe_serialization=True)
    tok.save_pretrained(args.out)
    # trust_remote_code checkpoints need their code files alongside the weights
    if os.path.isdir(str(args.base)):
        for f in ("modeling_lfm3.py", "configuration_lfm3.py", "lfm3_conv.py", "chat_template.jinja"):
            src = os.path.join(args.base, f)
            if os.path.exists(src):
                shutil.copy(src, os.path.join(args.out, f))
    else:
        print("note: --base is a hub id; copy the custom modeling files from it into", args.out)
    total = sum(os.path.getsize(os.path.join(args.out, f)) for f in os.listdir(args.out))
    print(f"saved {args.out}  {total/1e9:.2f} GB")


if __name__ == "__main__":
    main()