Upload 2 files
Browse filesFiles changed (2)
- engine/build_drafter.pyAdded+92
- engine/serve.shAdded+41
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""Prepare the draft model that RightNow Mini's engine uses for speculative decoding.
python engine/build_drafter.py <model dir> <drafter dir> <out dir> [--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 theengine 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 enginewithout 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 jsonimport pathlibimport shutilimport sysimport 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:]))1234567891011121314151617181920212223242526272829303132333435363738394041#!/usr/bin/env bash# RightNow Mini's engine: one command, an OpenAI-compatible server on one GPU.## MODEL_DIR=/path/to/model DRAFTER_DIR=/path/to/Inkling-2-Mini-DFlash2 bash engine/serve.sh## What it is: vLLM (the image below, pinned by digest) with speculative decoding through a prepared copy of the# published draft model `incoai/Inkling-2-Mini-DFlash2` (see engine/build_drafter.py for what is prepared and why).# The model checks every drafted token. Measured speed and the token-by-token comparison with the stock engine are# in results/speed.md.## Variables: GPU (0), PORT (8000), HOST (127.0.0.1), NAME (rightnow-mini), SERVED (rightnow-mini), DRAFT=0 for no drafting.set -euMODEL_DIR=${MODEL_DIR:?the folder with the model weights}GPU=${GPU:-0}; PORT=${PORT:-8000}; HOST=${HOST:-127.0.0.1}; NAME=${NAME:-rightnow-mini}; SERVED=${SERVED:-rightnow-mini}IMAGE=${IMAGE:-vllm/vllm-openai@sha256:3f80650e404965216b36042caca709598d4163342366d86c4247a06541eca81d}DOCKER=${DOCKER:-docker}HERE=$(cd "$(dirname "$0")" && pwd)ARGS=(--model /model --served-model-name "$SERVED" --tensor-parallel-size 1 --reasoning-parser inkling --enable-auto-tool-choice --tool-call-parser inkling --host "$HOST" --port "$PORT")MOUNTS=(-v "$MODEL_DIR":/model:ro)if [ "${DRAFT:-1}" = 1 ]; then DRAFTER_DIR=${DRAFTER_DIR:?the folder with incoai/Inkling-2-Mini-DFlash2 (or DRAFT=0)} PREPARED=${PREPARED:-$DRAFTER_DIR-prepared} if [ ! -s "$PREPARED/model.safetensors" ]; then mkdir -p "$PREPARED" $DOCKER run --rm --entrypoint python3 -v "$MODEL_DIR":/model:ro -v "$DRAFTER_DIR":/drafter:ro -v "$PREPARED":/prepared \ -v "$HERE":/engine:ro "$IMAGE" /engine/build_drafter.py /model /drafter /prepared fi MOUNTS+=(-v "$PREPARED":/drafter:ro) ARGS+=(--speculative-config '{"method":"dflash","model":"/drafter","num_speculative_tokens":7,"draft_sample_method":"probabilistic"}')fi$DOCKER rm -f "$NAME" >/dev/null 2>&1 || true$DOCKER run -d --name "$NAME" --gpus "device=$GPU" --ipc=host --network host "${MOUNTS[@]}" \ -e VLLM_NO_USAGE_STATS=1 -e DO_NOT_TRACK=1 "$IMAGE" "${ARGS[@]}" ${EXTRA:-}echo "starting $NAME on GPU $GPU, http://$HOST:$PORT/v1 (model id: $SERVED)"for i in $(seq 1 180); do if curl -s -m 3 "http://$HOST:$PORT/v1/models" | grep -q '"id"'; then echo "ready after $((i * 5)) s"; exit 0; fi if [ -z "$($DOCKER ps -q -f name="^$NAME$")" ]; then echo "the server exited:"; $DOCKER logs --tail 30 "$NAME" 2>&1 | cut -c1-300; exit 1; fi sleep 5doneecho "not ready after 900 s"; exit 1engine/build_drafter.pyAdded+92
engine/serve.shAdded+41