nextgpt-chapter6-report / code /scripts /merge_vicuna_streaming.py
CollinMa's picture
Publish NExT-GPT course code and actual execution records
15c46ce verified
Raw History Blame Contribute Delete
3.61 kB
"""Restore Vicuna v0 without holding two complete 7B models in memory."""
import gc
import json
import shutil
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from settings import WEIGHTS, MODELS, weight_paths
def add_base_to_delta(delta, base, name):
if delta.shape == base.shape:
delta.add_(base)
elif name in ("model.embed_tokens.weight", "lm_head.weight") and delta.shape[0] == base.shape[0]+1 and delta.shape[1:] == base.shape[1:]:
# FastChat v0 adds one PAD row, zeroes the new base row, then adds delta.
delta[:base.shape[0]].add_(base)
else:
raise ValueError(f"Unexpected shape for {name}: {tuple(base.shape)} vs {tuple(delta.shape)}")
return delta
def restore():
import torch
from safetensors import safe_open
base_dir = WEIGHTS / "sources" / "llama"
delta_dir = WEIGHTS / "sources" / "vicuna_delta"
target = weight_paths()["vicuna"]
if (target / "merge_complete.json").is_file():
print("Vicuna v0 already restored.")
return
base_index = json.loads((base_dir / "model.safetensors.index.json").read_text())
delta_index = json.loads((delta_dir / "pytorch_model.bin.index.json").read_text())
if set(base_index["weight_map"]) != set(delta_index["weight_map"]):
raise ValueError("Base and delta keys do not match")
target.mkdir(parents=True, exist_ok=True)
buffer, buffered_bytes, file_index, weights, total_bytes = {}, 0, 0, {}, 0
def flush():
nonlocal buffer, buffered_bytes, file_index
if not buffer:
return
file_index += 1
filename = f"pytorch_model-{file_index:05d}.bin"
temporary = target / (filename + ".part")
torch.save(buffer, temporary)
temporary.replace(target / filename)
weights.update({name: filename for name in buffer})
buffer, buffered_bytes = {}, 0
gc.collect()
with torch.no_grad():
for delta_file in sorted(set(delta_index["weight_map"].values())):
print("Loading delta shard " + delta_file, flush=True)
state = torch.load(delta_dir / delta_file, map_location="cpu")
for name in list(state):
value = state.pop(name)
with safe_open(str(base_dir / base_index["weight_map"][name]), framework="pt", device="cpu") as source:
base = source.get_tensor(name)
add_base_to_delta(value, base, name)
del base
size = value.numel()*value.element_size()
if buffered_bytes+size > 1_000_000_000:
flush()
buffer[name] = value
buffered_bytes += size
total_bytes += size
del value
del state
gc.collect()
flush()
(target / "pytorch_model.bin.index.json").write_text(json.dumps({"metadata": {"total_size": total_bytes}, "weight_map": weights}, indent=2))
for item in delta_dir.iterdir():
if item.is_file() and (item.suffix in (".json", ".model")) and item.name != "pytorch_model.bin.index.json":
shutil.copyfile(item, target / item.name)
(target / "merge_complete.json").write_text(json.dumps({"base": MODELS["llama"], "delta": MODELS["vicuna_delta"],
"method": "Streaming FastChat v0 PAD-row zero initialization plus delta", "parameters": len(weights)}, indent=2))
print(f"Vicuna v0 restored: {len(weights)} tensors, {total_bytes/2**30:.2f} GiB", flush=True)
if __name__ == "__main__":
restore()