""" 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()