File size: 5,230 Bytes
86599c0 | 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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | import argparse
import json
from pathlib import Path
import re
from shutil import copy2
import torch
from safetensors import safe_open
from safetensors.torch import save_file
from safetensors.torch import load_file
from block_fp8 import configure_serialized_experts, pack_experts
import sys
sys.path.insert(0, str(Path(__file__).absolute().parents[1] / "runtime"))
from detector_runtime.fp8 import quantize_experts
ROUTED = re.compile(r"model.layers.(\d+).mlp.experts.(gate_up|down)_proj")
SHARED = re.compile(
r"model.layers.(\d+).mlp.shared_expert.(gate_proj|up_proj|down_proj).weight"
)
def merge_routed(weight, a, b, alpha, storage):
merged = torch.empty_like(weight)
for start in range(0, weight.shape[0], 8):
part = slice(start, start + 8)
quantized, scales = quantize_experts(weight[part], storage)
rounded = quantized.float() * scales[:, None, None]
merged[part] = rounded + torch.bmm(b[part], a[part]) * (alpha / a.shape[1])
return merged
def export(base, checkpoint, config, output, *, fp8=False, device="cuda"):
torch.set_num_threads(8)
output.mkdir(parents=True, exist_ok=True)
state = load_file(checkpoint)
source = json.loads((base / "model.safetensors.index.json").read_text())[
"weight_map"
]
index, consumed = {}, set()
ignored = {"lm_head"}
alpha = config["lora_alpha"]
storage = config.get("expert_storage", "int8")
for shard in sorted(set(source.values())):
tensors = {}
with safe_open(base / shard, framework="pt") as handle:
for name in handle.keys():
if name == "lm_head.weight":
continue
elif name.startswith("model.language_model."):
dest = "model." + name.removeprefix("model.language_model.")
else:
continue
weight = handle.get_tensor(name)
routed, shared = ROUTED.fullmatch(dest), SHARED.fullmatch(dest)
if routed:
layer, kind = routed.groups()
prefix = f"backbone.layers.{layer}.mlp.experts.{kind}_lora"
weight = merge_routed(
weight.to(device),
state[prefix + ".a"].to(device),
state[prefix + ".b"].to(device),
alpha,
storage,
)
if fp8:
weight, scales = pack_experts(weight)
tensors[dest + "_scale_inv"] = scales.cpu()
consumed.update((prefix + ".a", prefix + ".b"))
elif shared:
layer, kind = shared.groups()
prefix = f"backbone.layers.{layer}.mlp.shared_expert.{kind}"
a, b = state[prefix + ".a"], state[prefix + ".b"]
weight = (
weight.to(device=device, dtype=torch.float32)
+ (b.to(device) @ a.to(device)) * (alpha / a.shape[0])
).to(weight.dtype)
consumed.update((prefix + ".a", prefix + ".b"))
tensors[dest] = weight.contiguous().cpu()
if dest.endswith(".weight"):
ignored.add(dest.removesuffix(".weight"))
if tensors:
save_file(tensors, output / shard)
index.update(dict.fromkeys(tensors, shard))
print("EXPORTED", shard, flush=True)
assert set(state) - consumed == {
key for key in state if key.startswith(("head.", "attention_pool.", "donor."))
}
text = json.loads((base / "config.json").read_text())["text_config"]
if fp8:
configure_serialized_experts(text, ignored)
text["architectures"] = ["Detector35ForPooling"]
(output / "config.json").write_text(json.dumps(text, indent=2) + "\n")
for file in base.iterdir():
if file.is_file() and file.name.startswith(
("tokenizer", "vocab", "merges", "special_tokens", "chat_template")
):
copy2(file, output / file.name)
(output / "model.safetensors.index.json").write_text(
json.dumps({"weight_map": index}) + "\n"
)
if __name__ == "__main__":
import tempfile
from huggingface_hub import snapshot_download
parser = argparse.ArgumentParser()
parser.add_argument("output", type=Path)
parser.add_argument(
"--fp8",
action="store_true",
help="Export block-FP8 routed expert weights for H100",
)
args = parser.parse_args()
root = Path(__file__).absolute().parents[1]
config = json.loads((root / "model-config.json").read_text())
base = Path(
snapshot_download(config["base_repository"], revision=config["base_revision"])
)
if args.output.exists():
parser.error("Choose a new output directory for the merged checkpoint.")
args.output.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=args.output.parent) as tmp:
staged = Path(tmp) / "merged"
export(base, root / "trainable.safetensors", config, staged, fp8=args.fp8)
staged.rename(args.output)
|