"""Merge a saved LoRA adapter into the base model, laid out like train_lora.py --merge-to does. usage: merge.py """ import os import shutil import sys import torch from peft import PeftModel from transformers import AutoModelForImageTextToText, AutoTokenizer base, adapter, out = sys.argv[1:4] dev = "cuda" if torch.cuda.is_available() else "cpu" model = AutoModelForImageTextToText.from_pretrained(base, dtype=torch.bfloat16).to(dev) model = PeftModel.from_pretrained(model, adapter) merged = model.merge_and_unload() merged.save_pretrained(out, safe_serialization=True) AutoTokenizer.from_pretrained(base).save_pretrained(out) src = base if os.path.isdir(base) else None if src is None: from huggingface_hub import snapshot_download src = snapshot_download(base, allow_patterns=["*.json", "*.jinja", "*.txt"]) for f in os.listdir(src): # processor and template files the server expects; never the base shard index if f.endswith((".json", ".jinja", ".txt")) and not f.endswith(".index.json") and not os.path.exists(os.path.join(out, f)): shutil.copy(os.path.join(src, f), os.path.join(out, f)) print("MERGED MODEL SAVED:", out, "| files:", sorted(os.listdir(out)))