Download code/merge.py from badr7/rapidchat-data: direct link, hf CLI and curl.
- Browser
- Download file 1.25 kB
-
https://huggingface.co/datasets/badr7/rapidchat-data/resolve/main/code/merge.py
- Command line
-
hf download hf://datasets/badr7/rapidchat-data/code/merge.py
-
curl -L -o merge.py https://huggingface.co/datasets/badr7/rapidchat-data/resolve/main/code/merge.py
1.25 kB
| """Merge a saved LoRA adapter into the base model, laid out like train_lora.py --merge-to does. | |
| usage: merge.py <base model> <adapter dir> <out dir>""" | |
| 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))) | |