Token Classification
lora
AI-Detector-35BA3B / gpu /export.py
matthewagi's picture matt's picture
Initial model release
86599c0
Raw History Blame Contribute Delete
5.23 kB
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)