Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files50 unmodified lines51525354555657585960616263646566676869707144 unmodified lines11611711810410511912012112212312412512610812712812913013111013213313413511313613713811613914011814114214314414514614714814915015115215315415515615715815916016116216316416514 unmodified lines1801811821831841851861421871881891909 unmodified lines2002012022032042052062072 unmodified lines21021121221316621421516821621721821922022122222322422522622722817622923023123255 unmodified lines28828929029129229329429523829629729829910 unmodified lines3103113122552563133143153163172593183193203218 unmodified lines330331332333334335336337338276339340341342278 unmodified lines6216226235616246256266273 unmodified lines63163263363463563663763857263964064164263 unmodified lines70670770864270971071171248 unmodified lines761762763697764765766767768769155 unmodified lines92592692785992892993093150 unmodified lines r"^(?: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 lines
def resolve_key(name, base_keys): """Map an adapter-side parameter name to a base checkpoint key (exact or known prefix swaps).""" cands = [name] """ 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."):] cands.extend(["model." + tail, "model.llm." + tail]) 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."): cands.append("model." + name) 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."):] cands.extend(["model.language_model." + tail, "model." + tail]) prefixes.extend(["model.language_model." + tail, "model." + tail]) elif name.startswith("model."): tail = name[len("model."):] cands.extend(["model.language_model." + tail, "model.llm." + tail]) prefixes.extend(["model.llm." + tail, "model.language_model." + tail]) elif name.startswith("layers."): cands.extend(["model.language_model." + name, "model." + name]) prefixes.extend(["model.llm." + name, "model.language_model." + name, "model." + name])
# Expand optional HF `.linear` wrapper removal + Inkling-2 projection renames seen = 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 lines Returns: plan: {base_key: (A, B, scale)} LoRA deltas replace: {base_key: tensor} full-weight replacements (modules_to_save) renames: [(adapter_key, base_key)] for logging/verification problems: [str] """ use_rslora = bool(adapter_cfg.get("use_rslora", False)) groups, replace, problems = {}, {}, [] groups, replace, renames, problems = {}, {}, [], []
for k, v in adapter_sd.items(): m = LORA_RE.match(k)9 unmodified lines bk = resolve_key(name, base_keys) if bk is not None: replace[bk] = v if bk != name: renames.append((name, bk)) else: problems.append(f"Unsupported adapter key: {k}")
2 unmodified lines if "A" not in ab or "B" not in ab: problems.append(f"Incomplete LoRA pair: {mod}") continue adapter_weight_key = mod + ".weight" bk = resolve_key(mod + ".weight", base_keys) bk = resolve_key(adapter_weight_key, base_keys) if bk is None: problems.append(f"No base key for: {mod}.weight") problems.append(f"No base key for: {adapter_weight_key}") continue if bk in plan: problems.append(f"Duplicate mapping onto base key: {bk}") continue A, 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 / r plan[bk] = (A, B, float(scale)) if bk != adapter_weight_key: renames.append((adapter_weight_key, bk))
return plan, replace, problems return plan, replace, renames, problems
def apply_lora(w, A, B, scale, fan_in_fan_out):55 unmodified lines lo = 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(16, dim=-1) 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 lines if len(shape) == 3: num_experts, out_dim, packed_in = shape out = torch.empty((num_experts, out_dim, packed_in * 2), dtype=torch.bfloat16) a_is_scalar = len(a_slice.get_shape()) == 0 a_full = f.get_tensor(name + "_amax") if a_is_scalar else None a_shape = a_slice.get_shape() a_per_expert = len(a_shape) >= 1 and a_shape[0] == num_experts a_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_full if a_is_scalar else a_slice[start:end] a_c = a_slice[start:end] if a_per_expert else a_full out[start:end] = _deq_nvfp4_block( w_slice[start:end], s_slice[start:end], a_c, denom )8 unmodified lines
def _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_e8m0fnu exp = scale.contiguous().view(torch.uint8).to(torch.float32) - 127.0 block = torch.exp2(exp).repeat_interleave(32, dim=-1) block = 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, problems = parse_adapter(adapter_sd, adapter_cfg, base_keys) 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 lines yield log("❌ Nothing to merge.") return
rename_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" f"✅ Mapped {len(plan)} LoRA modules, {len(replace)} full-weight replacements{rename_note}" )
# -------------------------63 unmodified lines del tensors gc.collect()
yield log(f"🔄 [{si}/{len(main_shards)}] Uploading {fname} ({n_t} tensors)") 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 lines
tensors[k] = t new_weight_map[k] = out_fname written_dtypes[k] = TORCH_DTYPE_NAMES.get(t.dtype, str(t.dtype).replace("torch.", "")) written_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`** 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