Spaces:
Running on Zero
Running on Zero
Delete app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466import osimport jsonimport shutilimport tempfilefrom contextlib import ExitStack
import gradio as grfrom huggingface_hub import HfApi, hf_hub_download, snapshot_downloadfrom safetensors import safe_openfrom safetensors.torch import save_file
# ZeroGPU Spaces require at least one @spaces.GPU function at startup.# The actual work below is CPU/disk only, so it is NOT decorated (no 290s cap).try: import spaces
@spaces.GPU(duration=1) def _zerogpu_stub(): return Noneexcept ImportError: pass
# =====================================================# Config# =====================================================
DEFAULT_MTP_BASE = "Qwen/Qwen3.5-4B"
# Fields that must match between model and MTP base for the MTP head to be mergeableCOMPAT_KEYS = ( "hidden_size", "intermediate_size", "num_attention_heads", "num_key_value_heads", "head_dim",)
SRC_IGNORE = [ "*/*", "*.mp4", "*.MP4", "*.bin", "*.pt", "*.pth", "*.gguf", "*.onnx", "*.h5", "*.msgpack", "*.ot", "README.md", ".gitattributes",]
# =====================================================# Helpers# =====================================================
def parse_size(size): s = str(size).strip().upper().replace(" ", "") for suffix, mult in ( ("GIB", 2**30), ("MIB", 2**20), ("KIB", 2**10), ("GB", 10**9), ("MB", 10**6), ("KB", 10**3), ): if s.endswith(suffix): return int(float(s[: -len(suffix)]) * mult) return int(s)
def is_mtp_key(key): return key.startswith("mtp.") or ".mtp." in key
def read_header(path): """Return {tensor_key: nbytes} from a safetensors header without loading tensors.""" with open(path, "rb") as f: n = int.from_bytes(f.read(8), "little") header = json.loads(f.read(n)) header.pop("__metadata__", None) return {k: v["data_offsets"][1] - v["data_offsets"][0] for k, v in header.items()}
def collect_entries(paths, only_mtp=False): """List of (key, file_path, nbytes).""" entries = [] for p in paths: for k, n in read_header(p).items(): if only_mtp and not is_mtp_key(k): continue entries.append((k, p, n)) return entries
def text_cfg(cfg): return cfg.get("text_config", cfg)
def check_compat(model_cfg, base_cfg): m, b = text_cfg(model_cfg), text_cfg(base_cfg) return [ f"{k}: model={m[k]} base={b[k]}" for k in COMPAT_KEYS if k in m and k in b and m[k] != b[k] ]
def patch_config(cfg_path, base_cfg, merged): """Make sure MTP fields exist in the output config.""" with open(cfg_path, "r", encoding="utf-8") as f: cfg = json.load(f) t, bt = text_cfg(cfg), text_cfg(base_cfg) patched = []
if "mtp_num_hidden_layers" in bt: cur = t.get("mtp_num_hidden_layers") if cur is None or (merged and not cur): t["mtp_num_hidden_layers"] = bt["mtp_num_hidden_layers"] patched.append("mtp_num_hidden_layers")
if "mtp_use_dedicated_embeddings" in bt and "mtp_use_dedicated_embeddings" not in t: t["mtp_use_dedicated_embeddings"] = bt["mtp_use_dedicated_embeddings"] patched.append("mtp_use_dedicated_embeddings")
if patched: with open(cfg_path, "w", encoding="utf-8") as f: json.dump(cfg, f, indent=2, ensure_ascii=False) return patched
def fetch_base_mtp(base_id, token, work_dir): """Download only the base-model shards that contain MTP tensors.""" base_dir = os.path.join(work_dir, "base") try: idx_path = hf_hub_download( base_id, "model.safetensors.index.json", token=token, local_dir=base_dir ) with open(idx_path, "r", encoding="utf-8") as f: weight_map = json.load(f)["weight_map"] files = sorted({fn for k, fn in weight_map.items() if is_mtp_key(k)}) except Exception: files = ["model.safetensors"] # unsharded base
paths = [hf_hub_download(base_id, fn, token=token, local_dir=base_dir) for fn in files] return collect_entries(paths, only_mtp=True)
def copy_aux_files(src_dir, out_dir): """Copy root-level config/tokenizer/processor/etc. (ignores subfolders, weights, index, and .mp4).""" for fn in os.listdir(src_dir): src_path = os.path.join(src_dir, fn) if not os.path.isfile(src_path): continue if ( fn.endswith(".safetensors") or fn == "model.safetensors.index.json" or fn.lower().endswith(".mp4") ): continue shutil.copy2(src_path, os.path.join(out_dir, fn))
def pack_shards(entries, max_bytes): shards, cur, cur_size = [], [], 0 for e in entries: if cur and cur_size + e[2] > max_bytes: shards.append(cur) cur, cur_size = [], 0 cur.append(e) cur_size += e[2] if cur: shards.append(cur) return shards
# =====================================================# Main# =====================================================
def reshard_with_mtp( model_name, new_repo_id, hf_token, max_shard_size="4.4GB", commit_message="", mtp_base=DEFAULT_MTP_BASE,): logs = []
def log(msg): logs.append(msg) return "\n".join(logs)
work = None
try: # ------------------------- # Validate inputs # ------------------------- model_name = (model_name or "").strip() new_repo_id = (new_repo_id or "").strip() hf_token = (hf_token or "").strip() mtp_base = (mtp_base or "").strip() or DEFAULT_MTP_BASE commit_message = (commit_message or "").strip() or "Upload sharded model"
if not model_name or not new_repo_id or not hf_token: yield log("β Model name, repo id, and token are required.") return if "/" not in new_repo_id: yield log("β Repo id must be 'username/repo-name'.") return
try: max_bytes = parse_size(max_shard_size or "4.4GB") except Exception: yield log(f"β Invalid max shard size: {max_shard_size}") return
# ------------------------- # Login + repo # ------------------------- api = HfApi(token=hf_token) api.whoami() yield log("β
Hugging Face login successful")
api.create_repo( repo_id=new_repo_id, repo_type="model", private=True, exist_ok=True ) yield log(f"β
Repo ready: {new_repo_id}")
work = tempfile.mkdtemp(prefix="reshard_") src_dir = os.path.join(work, "src") out_dir = os.path.join(work, "out") os.makedirs(out_dir, exist_ok=True)
# ------------------------- # Download source model (files only, no model load) # ------------------------- yield log(f"π Downloading: {model_name}") snapshot_download( repo_id=model_name, local_dir=src_dir, token=hf_token, ignore_patterns=SRC_IGNORE, )
src_files = sorted( os.path.join(src_dir, f) for f in os.listdir(src_dir) if f.endswith(".safetensors") and os.path.isfile(os.path.join(src_dir, f)) ) if not src_files: yield log("β No .safetensors weights found in source model.") return
entries = collect_entries(src_files) yield log(f"β
Source: {len(src_files)} file(s), {len(entries)} tensors")
# ------------------------- # MTP check / merge from base # ------------------------- base_cfg = None try: base_cfg_path = hf_hub_download( mtp_base, "config.json", token=hf_token, local_dir=os.path.join(work, "base"), ) with open(base_cfg_path, "r", encoding="utf-8") as f: base_cfg = json.load(f) except Exception as e: yield log(f"β οΈ Could not fetch base config ({mtp_base}): {e}")
src_mtp = [e for e in entries if is_mtp_key(e[0])] merged = False
if src_mtp: yield log(f"β
MTP present in source: {len(src_mtp)} tensors (kept as-is)") else: yield log(f"β οΈ No MTP tensors in source. Merging from base: {mtp_base}")
if base_cfg is None: yield log("β Base config required to validate MTP compatibility.") return
with open(os.path.join(src_dir, "config.json"), "r", encoding="utf-8") as f: model_cfg = json.load(f) mismatches = check_compat(model_cfg, base_cfg) if mismatches: yield log( "β Architecture mismatch, cannot merge base MTP:\n " + "\n ".join(mismatches) ) return
yield log("π Fetching MTP tensors from base...") base_mtp = fetch_base_mtp(mtp_base, hf_token, work) if not base_mtp: yield log(f"β No MTP tensors found in base model: {mtp_base}") return
entries = entries + base_mtp merged = True yield log(f"β
Merged {len(base_mtp)} MTP tensors from {mtp_base}")
# ------------------------- # Reshard (tensor-level, key names preserved) # ------------------------- shards = pack_shards(entries, max_bytes) n = len(shards) yield log(f"π Writing {n} shard(s) (max_shard_size={max_shard_size})")
weight_map, total_size = {}, 0
with ExitStack() as stack: handles = {}
def get_tensor(path, key): if path not in handles: handles[path] = stack.enter_context( safe_open(path, framework="pt", device="cpu") ) return handles[path].get_tensor(key)
for i, shard in enumerate(shards, start=1): fname = ( "model.safetensors" if n == 1 else f"model-{i:05d}-of-{n:05d}.safetensors" ) tensors = {k: get_tensor(p, k) for k, p, _ in shard} save_file(tensors, os.path.join(out_dir, fname), metadata={"format": "pt"})
for k, _, nbytes in shard: weight_map[k] = fname total_size += nbytes
del tensors yield log(f" shard {i}/{n}: {fname}")
if n > 1: with open( os.path.join(out_dir, "model.safetensors.index.json"), "w", encoding="utf-8" ) as f: json.dump( {"metadata": {"total_size": total_size}, "weight_map": weight_map}, f, indent=2, )
# ------------------------- # Aux files + config patch # ------------------------- copy_aux_files(src_dir, out_dir) yield log("β
Config / tokenizer / processor files copied")
if base_cfg is not None: patched = patch_config(os.path.join(out_dir, "config.json"), base_cfg, merged) if patched: yield log(f"β
Config patched: {', '.join(patched)}")
# ------------------------- # Verify # ------------------------- out_mtp = sum(1 for k in weight_map if is_mtp_key(k)) if out_mtp == 0: yield log("β Output has no MTP tensors. Aborting upload.") return yield log(f"β
Verified: {out_mtp} MTP tensors in output ({len(weight_map)} total)")
# ------------------------- # Upload # ------------------------- yield log("π Uploading to HuggingFace...") yield log(f"π Commit message: {commit_message}")
api.upload_folder( repo_id=new_repo_id, repo_type="model", folder_path=out_dir, revision="main", commit_message=commit_message, delete_patterns=["*.safetensors", "model.safetensors.index.json"], )
yield log(f"π Upload completed: https://huggingface.co/{new_repo_id}")
except Exception as e: yield log(f"β Error: {str(e)}")
finally: if work and os.path.isdir(work): shutil.rmtree(work, ignore_errors=True)
# =====================================================# Gradio UI# =====================================================
with gr.Blocks(theme="soft") as demo:
gr.Markdown( """# π Qwen3.5 Model Sharder & Re-Uploader (MTP-safe)
This tool will:
1οΈβ£ Download a **Qwen3.5 model** 2οΈβ£ Check for **MTP** tensors; if missing, merge them from the **base model** 3οΈβ£ Re-save with **smaller shards** (tensor-level, key names preserved) 4οΈβ£ Upload to a **private Hugging Face repository**""" )
with gr.Row():
with gr.Column(scale=2):
model_name = gr.Textbox( label="Original Model Name", value="Qwen/Qwen3.5-4B" )
mtp_base = gr.Textbox( label="MTP Base Model (used only if source has no MTP)", value=DEFAULT_MTP_BASE )
new_repo_id = gr.Textbox( label="New Repository ID", placeholder="username/my-private-qwen3.5" )
hf_token = gr.Textbox( label="HuggingFace Write Token", type="password", placeholder="hf_xxxxxxxxx" )
max_shard_size = gr.Textbox( label="Max Shard Size", value="4.4GB" )
commit_message = gr.Textbox( label="Commit Message", placeholder="Upload sharded model (default used if left empty)", value="Upload sharded model", lines=2 )
run_btn = gr.Button( "π Shard & Upload Model", variant="primary" )
with gr.Column(scale=3):
logs = gr.Textbox( label="Process Logs", lines=20, interactive=False, autoscroll=True )
run_btn.click( fn=reshard_with_mtp, inputs=[model_name, new_repo_id, hf_token, max_shard_size, commit_message, mtp_base], outputs=logs )
# =====================================================# Launch# =====================================================
if __name__ == "__main__": demo.launch()app.pyDeleted-466