Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files50 unmodified lines51525354555644 unmodified lines10110210310410510610710810911011111211311411511611711811912012114 unmodified lines1361371381391401411421431441459 unmodified lines1551561571581591602 unmodified lines16316416516616716816917017117217317417517617717817955 unmodified lines23523623723823924024110 unmodified lines2522532542552562572582592602612628 unmodified lines271272273274275276277278279278 unmodified lines5585595605615625635643 unmodified lines56856957057157257357457563 unmodified lines63964064164264364464548 unmodified lines694695696697698699700155 unmodified lines85685785885986086186250 unmodified linesr"^(?:base_model\.model\.)?(?P<mod>.+)\.lora_(?P<ab>[AB])(?:\.[^.]+)?\.weight$")E2M1_TABLE = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0,44 unmodified linesdef resolve_key(name, base_keys):"""Map an adapter-side parameter name to a base checkpoint key (exact or known prefix swaps)."""cands = [name]if name.startswith("model.language_model."):tail = name[len("model.language_model."):]cands.extend(["model." + tail, "model.llm." + tail])elif name.startswith("language_model."):cands.append("model." + name)elif name.startswith("model.llm."):tail = name[len("model.llm."):]cands.extend(["model.language_model." + tail, "model." + tail])elif name.startswith("model."):tail = name[len("model."):]cands.extend(["model.language_model." + tail, "model.llm." + tail])elif name.startswith("layers."):cands.extend(["model.language_model." + name, "model." + name])for c in cands:if c in base_keys:14 unmodified linesReturns:plan: {base_key: (A, B, scale)} LoRA deltasreplace: {base_key: tensor} full-weight replacements (modules_to_save)problems: [str]"""use_rslora = bool(adapter_cfg.get("use_rslora", False))groups, replace, problems = {}, {}, []for k, v in adapter_sd.items():m = LORA_RE.match(k)9 unmodified linesbk = resolve_key(name, base_keys)if bk is not None:replace[bk] = velse:problems.append(f"Unsupported adapter key: {k}")2 unmodified linesif "A" not in ab or "B" not in ab:problems.append(f"Incomplete LoRA pair: {mod}")continuebk = resolve_key(mod + ".weight", base_keys)if bk is None:problems.append(f"No base key for: {mod}.weight")continueA, B = ab["A"], ab["B"]r = A.shape[0]alpha = module_alpha(mod, adapter_cfg)scale = alpha / (r ** 0.5) if use_rslora else alpha / rplan[bk] = (A, B, float(scale))return plan, replace, problemsdef apply_lora(w, A, B, scale, fan_in_fan_out):55 unmodified lineslo = E2M1_TABLE[(packed_u8 & 0x0F).long()]hi = E2M1_TABLE[(packed_u8 >> 4).long()]vals = torch.stack([lo, hi], dim=-1).flatten(-2)block = scale.float().repeat_interleave(16, dim=-1)outer = amax.float() / denom.float()while outer.ndim < vals.ndim:outer = outer.unsqueeze(-1)10 unmodified linesif len(shape) == 3:num_experts, out_dim, packed_in = shapeout = torch.empty((num_experts, out_dim, packed_in * 2), dtype=torch.bfloat16)a_is_scalar = len(a_slice.get_shape()) == 0a_full = f.get_tensor(name + "_amax") if a_is_scalar else Nonefor start in range(0, num_experts, chunk_size):end = min(start + chunk_size, num_experts)a_c = a_full if a_is_scalar else a_slice[start:end]out[start:end] = _deq_nvfp4_block(w_slice[start:end], s_slice[start:end], a_c, denom)8 unmodified linesdef _deq_mxfp8_block(values, scale):# E8M0 scale byte -> 2^(e - 127), works for both uint8 and float8_e8m0fnuexp = scale.contiguous().view(torch.uint8).to(torch.float32) - 127.0block = torch.exp2(exp).repeat_interleave(32, dim=-1)return (values.float() * block).to(torch.bfloat16)278 unmodified lines# -------------------------# Map adapter -> base (before any heavy download)# -------------------------plan, replace, problems = parse_adapter(adapter_sd, adapter_cfg, base_keys)if problems:shown = "\n ".join(problems[:15])more = f"\n ... +{len(problems) - 15} more" if len(problems) > 15 else ""3 unmodified linesyield log("❌ Nothing to merge.")returnyield log(f"✅ Mapped {len(plan)} LoRA modules, {len(replace)} full-weight replacements")# -------------------------63 unmodified linesdel tensorsgc.collect()yield log(f"🔄 [{si}/{len(main_shards)}] Uploading {fname} ({n_t} tensors)")api.upload_file(path_or_fileobj=out_path,path_in_repo=fname,48 unmodified linestensors[k] = tnew_weight_map[k] = out_fnamewritten_dtypes[k] = TORCH_DTYPE_NAMES.get(t.dtype, str(t.dtype).replace("torch.", ""))total_size += t.numel() * t.element_size()out_path = os.path.join(out_dir, out_fname)155 unmodified linesThis tool will:1️⃣ Download the **LoRA adapter** (`harness-hub/Inkling-2-Mini-pi-adapted-preview`) and base checkpoint (`thinkingmachines/Inkling-2-Mini`)2️⃣ Dequantize **NVFP4 (L0–19) & MXFP8 (L20–23)** experts to **BF16** in low-RAM chunks, merge `W + (alpha/r) · B·A` into attention projections, and preserve **`mtp.safetensors`**3️⃣ Stream-upload ~4.5 GB shards plus updated `config.json`, `hf_quant_config.json`, and `model.safetensors.index.json` to Hugging Face""")50 unmodified lines51525354555657585960616263646566676869707144 unmodified lines11611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416514 unmodified lines1801811821831841851861871881891909 unmodified lines2002012022032042052062072 unmodified lines21021121221321421521621721821922022122222322422522622722822923023123255 unmodified lines28828929029129229329429529629729829910 unmodified lines3103113123133143153163173183193203218 unmodified lines330331332333334335336337338339340341342278 unmodified lines6216226236246256266273 unmodified lines63163263363463563663763863964064164263 unmodified lines70670770870971071171248 unmodified lines761762763764765766767768769155 unmodified lines92592692792892993093150 unmodified linesr"^(?:base_model\.model\.)?(?P<mod>.+)\.lora_(?P<ab>[AB])(?:\.[^.]+)?\.weight$")# Hugging Face transformers -> native Thinking Machines Inkling-2 checkpoint key renamesINKLING2_HF_TO_NATIVE = ((".self_attn.q_proj.", ".attn.wq_du."),(".self_attn.k_proj.", ".attn.wk_dv."),(".self_attn.v_proj.", ".attn.wv_dv."),(".self_attn.o_proj.", ".attn.wo_ud."),(".self_attn.relative_position_bias.", ".attn.wr_du."),(".self_attn.r_proj.", ".attn.wr_du."),(".self_attn.gate_proj.", ".attn.gate_attn."),(".self_attn.sink_proj.", ".attn.attn_sink_proj."),(".self_attn.", ".attn."),(".mlp.experts.gate_up_proj.weight", ".mlp.experts.w13_weight"),(".mlp.experts.down_proj.weight", ".mlp.experts.w2_weight"),)E2M1_TABLE = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0,44 unmodified linesdef resolve_key(name, base_keys):"""Map an adapter-side parameter name (HF transformers / PEFT or vLLM) to a base checkpoint key,including Inkling-2's HF -> native Thinking Machines renames (e.g.model.language_model.layers.0.self_attn.q_proj.linear.weight -> model.llm.layers.0.attn.wq_du.weight)."""prefixes = [name]if name.startswith("model.language_model."):tail = name[len("model.language_model."):]prefixes.extend(["model.llm." + tail, "model." + tail, "language_model." + tail])elif name.startswith("language_model.model."):tail = name[len("language_model.model."):]prefixes.extend(["model.llm." + tail, "model.language_model." + tail, "model." + tail])elif name.startswith("language_model."):tail = name[len("language_model."):]prefixes.extend(["model.llm." + tail, "model.language_model." + tail, "model." + tail])elif name.startswith("model.llm."):tail = name[len("model.llm."):]prefixes.extend(["model.language_model." + tail, "model." + tail])elif name.startswith("model."):tail = name[len("model."):]prefixes.extend(["model.llm." + tail, "model.language_model." + tail])elif name.startswith("layers."):prefixes.extend(["model.llm." + name, "model.language_model." + name, "model." + name])# Expand optional HF `.linear` wrapper removal + Inkling-2 projection renamesseen = set()cands = []def add(c):if c not in seen:seen.add(c)cands.append(c)for p in prefixes:variants = [p]no_linear = re.sub(r"\.linear(\.(?:weight|bias))$", r"\1", p)if no_linear != p:variants.append(no_linear)for v in variants:add(v)for src, dst in INKLING2_HF_TO_NATIVE:if src in v:add(v.replace(src, dst, 1))for c in cands:if c in base_keys:14 unmodified linesReturns:plan: {base_key: (A, B, scale)} LoRA deltasreplace: {base_key: tensor} full-weight replacements (modules_to_save)renames: [(adapter_key, base_key)] for logging/verificationproblems: [str]"""use_rslora = bool(adapter_cfg.get("use_rslora", False))groups, replace, renames, problems = {}, {}, [], []for k, v in adapter_sd.items():m = LORA_RE.match(k)9 unmodified linesbk = resolve_key(name, base_keys)if bk is not None:replace[bk] = vif bk != name:renames.append((name, bk))else:problems.append(f"Unsupported adapter key: {k}")2 unmodified linesif "A" not in ab or "B" not in ab:problems.append(f"Incomplete LoRA pair: {mod}")continueadapter_weight_key = mod + ".weight"bk = resolve_key(adapter_weight_key, base_keys)if bk is None:problems.append(f"No base key for: {adapter_weight_key}")continueif bk in plan:problems.append(f"Duplicate mapping onto base key: {bk}")continueA, B = ab["A"], ab["B"]r = A.shape[0]alpha = module_alpha(mod, adapter_cfg)scale = alpha / (r ** 0.5) if use_rslora else alpha / rplan[bk] = (A, B, float(scale))if bk != adapter_weight_key:renames.append((adapter_weight_key, bk))return plan, replace, renames, problemsdef apply_lora(w, A, B, scale, fan_in_fan_out):55 unmodified lineslo = E2M1_TABLE[(packed_u8 & 0x0F).long()]hi = E2M1_TABLE[(packed_u8 >> 4).long()]vals = torch.stack([lo, hi], dim=-1).flatten(-2)group_size = vals.shape[-1] // scale.shape[-1]if vals.shape[-1] != scale.shape[-1] * group_size:raise ValueError(f"NVFP4 scale mismatch: vals={tuple(vals.shape)} scale={tuple(scale.shape)}")block = scale.float().repeat_interleave(group_size, dim=-1)outer = amax.float() / denom.float()while outer.ndim < vals.ndim:outer = outer.unsqueeze(-1)10 unmodified linesif len(shape) == 3:num_experts, out_dim, packed_in = shapeout = torch.empty((num_experts, out_dim, packed_in * 2), dtype=torch.bfloat16)a_shape = a_slice.get_shape()a_per_expert = len(a_shape) >= 1 and a_shape[0] == num_expertsa_full = None if a_per_expert else f.get_tensor(name + "_amax")for start in range(0, num_experts, chunk_size):end = min(start + chunk_size, num_experts)a_c = a_slice[start:end] if a_per_expert else a_fullout[start:end] = _deq_nvfp4_block(w_slice[start:end], s_slice[start:end], a_c, denom)8 unmodified linesdef _deq_mxfp8_block(values, scale):group_size = values.shape[-1] // scale.shape[-1]if values.shape[-1] != scale.shape[-1] * group_size:raise ValueError(f"MXFP8 scale mismatch: vals={tuple(values.shape)} scale={tuple(scale.shape)}")# E8M0 scale byte -> 2^(e - 127), works for both uint8 and float8_e8m0fnuexp = scale.contiguous().view(torch.uint8).to(torch.float32) - 127.0block = torch.exp2(exp).repeat_interleave(group_size, dim=-1)return (values.float() * block).to(torch.bfloat16)278 unmodified lines# -------------------------# Map adapter -> base (before any heavy download)# -------------------------plan, replace, renames, problems = parse_adapter(adapter_sd, adapter_cfg, base_keys)if problems:shown = "\n ".join(problems[:15])more = f"\n ... +{len(problems) - 15} more" if len(problems) > 15 else ""3 unmodified linesyield log("❌ Nothing to merge.")returnrename_note = ""if renames:sample = ", ".join(f"{a} -> {b}" for a, b in renames[:2])rename_note = f" (remapped {len(renames)} HF->native keys, e.g. {sample})"yield log(f"✅ Mapped {len(plan)} LoRA modules, {len(replace)} full-weight replacements{rename_note}")# -------------------------63 unmodified linesdel tensorsgc.collect()yield log(f"⬆️ [{si}/{len(main_shards)}] Uploading {fname} ({n_t} tensors)")api.upload_file(path_or_fileobj=out_path,path_in_repo=fname,48 unmodified linestensors[k] = tnew_weight_map[k] = out_fnamewritten_dtypes[k] = TORCH_DTYPE_NAMES.get(t.dtype, str(t.dtype).replace("torch.", ""))total_size += t.numel() * t.element_size()out_path = os.path.join(out_dir, out_fname)155 unmodified linesThis tool will:1️⃣ Download the **LoRA adapter** (`harness-hub/Inkling-2-Mini-pi-adapted-preview`) and base checkpoint (`thinkingmachines/Inkling-2-Mini`)2️⃣ Remap HF `self_attn.{q,k,v,o}_proj.linear` adapter keys to native `model.llm.layers.*.attn.{wq_du,wk_dv,wv_dv,wo_ud}` weights, dequantize **NVFP4 (L0–19) & MXFP8 (L20–23)** experts to **BF16**, and preserve **`mtp.safetensors`**3️⃣ Stream-upload ~4.5 GB shards plus updated `config.json`, `hf_quant_config.json`, and `model.safetensors.index.json` to Hugging Face""")
app.py+90-21