WeGen2-NVFP4 / wegen2_convert.py
HDiffusion's picture
Upload wegen2_convert.py with huggingface_hub
91b33da verified
Raw History Blame Contribute Delete
6.45 kB
"""Convert GrayShine/WeGen2 (49 BF16 shards, 123 GB) into the single nvfp4 file the engine loads.
Shards are downloaded into RAM, up to eight at a time, converted and dropped, so the BF16 original never touches the
disk and the run needs only the output's space (about 40 GB). The prompt enhancer in `prompt_enhancer/` is a separate
model (Qwen3-VL-30B-A3B-Instruct, unchanged) and isn't part of the file.
python tools/wegen2_convert.py <out.safetensors> [--work <dir>] [--parallel 8]
What the file holds:
* routed experts (`language_model.model.layers.N.mlp_{und,gen}.experts.{gate_up_proj,down_proj}`, shipped as BF16
[E, N, K]): nvfp4, every expert scaled on its own. The tensor itself is U8 [E, N, K/2], two E2M1 values a byte,
element 2i in the low nibble; `<name>_scale` is F8_E4M3 [E, N, K/16], one scale per 16 columns, row major;
`<name>_scale_2` is F32 [E], one per expert. A value is e2m1 * f32(e4m3) * scale_2[e]. Each block's scale is chosen
from a few candidates below its absolute maximum for the least squared error. gate_up_proj keeps the gate's rows
first, then the up rows.
* everything else (attention, shared experts, routers, norms, the depth-mixing projections, embeddings, lm_head, the
patch convolutions, llm2pixel and the time embedder): BF16, as shipped, under the original names.
* `tokenizer.json`: the text tokenizer's file, as U8 bytes.
* metadata: `wegen2` (the format version) and `config` (config.json).
`--work` keeps progress there, so an interrupted run resumes with the shards not yet written. Run with a Python that
has torch and CUDA, such as SwarmUI's python_embeded.
"""
import argparse
import json
import os
import pickle
import queue
import sys
import threading
import time
import torch
from safetensors.torch import load as st_load
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import nemotron_image_convert as nc # noqa: E402 - shares the download, nvfp4 and writer code
nc.REPO = "https://huggingface.co/GrayShine/WeGen2/resolve/main/"
FORMAT = "wegen2-nvfp4-v1"
def is_expert(name):
return ".experts." in name and name.endswith(("gate_up_proj", "down_proj"))
def experts_nvfp4(t, dev):
"""[E, N, K] -> (U8 [E, N, K/2], F8 [E, N, K/16], F32 [E], per-expert relative rms errors)."""
qs, scs, s2s, errs = [], [], [], []
for e in range(t.shape[0]):
q, sc, s2, rel = nc.nvfp4(t[e].to(dev, torch.float32))
qs.append(q.cpu())
scs.append(sc.cpu())
s2s.append(s2.cpu())
errs.append(rel)
return torch.stack(qs), torch.stack(scs), torch.stack(s2s).float(), errs
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("out")
ap.add_argument("--work", default=None, help="folder for progress, default next to the output")
ap.add_argument("--parallel", type=int, default=8, help="shards held in RAM at once, downloading or waiting")
args = ap.parse_args()
work = args.work or os.path.splitext(args.out)[0] + ".convert"
os.makedirs(work, exist_ok=True)
state_path = os.path.join(work, "state.pkl")
state = pickle.load(open(state_path, "rb")) if os.path.exists(state_path) else {}
done = set(state.get("done", []))
errs = state.get("errs", {})
dev = torch.device("cuda")
index = json.loads(nc.fetch("model.safetensors.index.json"))["weight_map"]
shards = sorted(set(index.values()))
writer = nc.Writer(args.out, state)
todo = [s for s in shards if s not in done]
print(f"{len(done)} shards done, {len(todo)} to go", flush=True)
# Downloads run ahead of the conversion, at most `parallel` shards in RAM at once.
slots = threading.Semaphore(args.parallel)
ready = queue.Queue()
pending = queue.Queue()
for s in todo:
pending.put(s)
def downloader():
while True:
try:
s = pending.get_nowait()
except queue.Empty:
return
slots.acquire()
t0 = time.time()
try:
data = nc.fetch(s, streams=4)
except Exception as e: # noqa: BLE001 - reported and stops the run
ready.put((s, e))
return
print(f"{s}: {len(data) / 1e9:.2f} GB in {time.time() - t0:.0f} s", flush=True)
ready.put((s, data))
for _ in range(min(args.parallel, len(todo))):
threading.Thread(target=downloader, daemon=True).start()
for _ in range(len(todo)):
s, data = ready.get()
if isinstance(data, Exception):
raise RuntimeError(f"{s}: {data}")
t0 = time.time()
tensors = st_load(data)
del data
for name in sorted(tensors):
t = tensors[name]
if index.get(name) != s:
raise ValueError(f"{s} holds {name}, which the index doesn't put there")
if t.dtype != torch.bfloat16:
raise ValueError(f"{name} is {t.dtype}, expected BF16")
if is_expert(name):
q, sc, s2, rel = experts_nvfp4(t, dev)
writer.add(name, q)
writer.add(name + "_scale", sc)
writer.add(name + "_scale_2", s2)
errs[name] = rel
else:
writer.add(name, t)
del tensors
slots.release()
done.add(s)
st = writer.state()
st.update(done=sorted(done), errs=errs)
with open(state_path + ".tmp", "wb") as f:
pickle.dump(st, f)
os.replace(state_path + ".tmp", state_path)
print(f"{s}: converted in {time.time() - t0:.0f} s, {len(done)}/{len(shards)} done, "
f"{writer.offset / 1e9:.2f} GB written", flush=True)
missing = set(index) - {n for n in index if index[n] in done}
if missing:
raise RuntimeError(f"tensors not converted: {sorted(missing)[:5]}")
meta = {"format": "pt", "wegen2": FORMAT, "config": nc.fetch("config.json").decode()}
tok = nc.fetch("tokenizer.json")
writer.tail["tokenizer.json"] = ("U8", [len(tok)], tok)
writer.finish(meta)
if errs:
e = torch.tensor([v for vs in errs.values() for v in vs])
print(f"expert nvfp4 relative rms error: mean {e.mean():.4f}, max {e.max():.4f} over {len(e)}", flush=True)
print(f"wrote {args.out}", flush=True)
if __name__ == "__main__":
sys.exit(main())