"""Prepare the draft model that RightNow Mini's engine uses for speculative decoding. python engine/build_drafter.py [--keep-softcap] The draft model is `incoai/Inkling-2-Mini-DFlash2` (Apache-2.0), a small block drafter published for Inkling 2 Mini. On a stock vLLM it proposes few tokens the model accepts, for three reasons this script removes without touching the engine or training anything: 1. Embeddings. The engine feeds a block drafter the model's raw embedding rows. The model itself reads its rows after its embedding norm (an RMS norm with a learned weight). The normalized table is written into the drafter's weights as `embed_tokens.weight`; the engine uses a drafter's own table when it ships one. 2. Layers. The drafter reads hidden states of the model at the layer visits its config lists. The engine shifts that list by one for this drafter type. The list is written under the key the engine reads as given. 3. Logit cap. The drafter was trained with its logit cap applied after its correction step; the engine applies it before. With the cap switched off in the drafter's config the engine's order no longer matters. `--keep-softcap` leaves the config's cap as published. The model still checks every drafted token. On this engine the text is still not token-identical to the engine without drafting, for this drafter and for the checkpoint's own draft head alike: results/speed.md has the table. Prints one JSON line with what it read and wrote. """ import json import pathlib import shutil import sys import time def main(argv): import torch from safetensors import safe_open from safetensors.torch import load_file, save_file if len(argv) < 3: print(__doc__) return 2 model_dir, drafter_dir, out = (pathlib.Path(x) for x in argv[:3]) keep_cap = "--keep-softcap" in argv[3:] t0 = time.time() cfg = json.loads((model_dir / "config.json").read_text()) text = cfg.get("text_config", cfg) hidden, eps = int(text["hidden_size"]), float(text.get("rms_norm_eps", 1e-6)) table = gain = None names = {} for f in sorted(model_dir.glob("model*.safetensors")): with safe_open(str(f), framework="pt") as sf: for k in sf.keys(): shape = list(sf.get_slice(k).get_shape()) if k.split(".")[-2:] == ["embed", "weight"] and len(shape) == 2 and shape[1] == hidden: # the input table, not `unembed` table, names["embedding"] = sf.get_tensor(k), k elif k.split(".")[-2:] == ["embed_norm", "weight"] and shape[-1] == hidden: gain, names["embedding_norm"] = sf.get_tensor(k).reshape(-1).float(), k if table is None or gain is None: print(json.dumps({"error": "embedding table or its norm weight not found in the model", "found": names})) return 1 normed = torch.empty_like(table) for i in range(0, table.shape[0], 16384): # in slices: the table has 201,024 rows x = table[i:i + 16384].float() normed[i:i + 16384] = (x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) * gain).to(table.dtype) weights = {} for f in sorted(drafter_dir.glob("*.safetensors")): weights.update(load_file(str(f))) if "embed_tokens.weight" in weights: print(json.dumps({"error": "this drafter already ships an embedding table"})) return 1 weights["embed_tokens.weight"] = normed.contiguous() out.mkdir(parents=True, exist_ok=True) save_file(weights, str(out / "model.safetensors")) dcfg = json.loads((drafter_dir / "config.json").read_text()) inner = dcfg.get("dflash_config") or {} if inner.get("target_layer_ids"): dcfg["eagle_aux_hidden_state_layer_ids"] = list(inner["target_layer_ids"]) cap_before = inner.get("final_logit_softcapping") if not keep_cap and "dflash_config" in dcfg: dcfg["dflash_config"]["final_logit_softcapping"] = 0.0 (out / "config.json").write_text(json.dumps(dcfg, indent=1)) for f in drafter_dir.iterdir(): if f.is_file() and f.suffix not in (".safetensors",) and f.name != "config.json" and not f.name.startswith("."): shutil.copy(f, out / f.name) print(json.dumps({"out": str(out), "read": names, "table_rows": table.shape[0], "hidden": hidden, "layer_ids": dcfg.get("eagle_aux_hidden_state_layer_ids"), "softcap": {"published": cap_before, "written": dcfg.get("dflash_config", {}).get("final_logit_softcapping")}, "bytes": (out / "model.safetensors").stat().st_size, "seconds": round(time.time() - t0, 1)})) return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))