File size: 2,841 Bytes
3ccaf5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
Merge a LoRA / QLoRA adapter into a base model at FP16 precision and save the
result as a standalone HuggingFace-format model directory.

Rationale:
    The old restored-inference path (scripts/run_inference_restored.py) loads
    the base in BnB-NF4, then calls PeftModel.merge_and_unload() on the 4-bit
    weights. PEFT itself warns that this merge introduces rounding errors:
        "Merge lora module to 4-bit linear may get different generations due
         to rounding errors."
    On top of that, HuggingFace `.generate()` runs one sample at a time, which
    is ~20-50x slower than vLLM's batched PagedAttention for a small model.

    This script merges the adapter into FP16 (which is lossless) and writes a
    standalone model. Downstream, run_inference.py can load the merged model
    via vLLM and (re-)quantize to NF4 at load time — giving the same target
    deployment (a 4-bit quantized, adapter-baked model) with dramatically
    better throughput and one fewer quantization round-trip.
"""

import argparse
import os


def main():
    parser = argparse.ArgumentParser(description="Merge LoRA adapter into FP16 base and save.")
    parser.add_argument("--model", required=True, help="Base model HF name or local path")
    parser.add_argument("--adapter", required=True, help="LoRA adapter directory")
    parser.add_argument("--output", required=True, help="Output directory for merged model")
    parser.add_argument("--dtype", default="bfloat16", choices=["float16", "bfloat16"],
                        help="Precision for the merged model on disk")
    args = parser.parse_args()

    if os.path.exists(os.path.join(args.output, "config.json")):
        print(f"[SKIP] Merged model already exists at: {args.output}")
        return

    import torch
    from transformers import AutoModelForCausalLM, AutoTokenizer
    from peft import PeftModel

    dtype = {"float16": torch.float16, "bfloat16": torch.bfloat16}[args.dtype]

    print(f"Loading base model in {args.dtype}: {args.model}")
    model = AutoModelForCausalLM.from_pretrained(
        args.model,
        torch_dtype=dtype,
        device_map="auto",
        trust_remote_code=True,
    )

    print(f"Applying adapter: {args.adapter}")
    model = PeftModel.from_pretrained(model, args.adapter)
    print("Merging adapter into base weights")
    model = model.merge_and_unload()

    os.makedirs(args.output, exist_ok=True)
    print(f"Saving merged model to: {args.output}")
    model.save_pretrained(args.output, safe_serialization=True)

    tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True)
    tokenizer.save_pretrained(args.output)

    if torch.cuda.is_available():
        print(f"Peak GPU memory: {torch.cuda.max_memory_allocated() / 1e9:.1f} GB")
    print("Done.")


if __name__ == "__main__":
    main()