#!/usr/bin/env python3 """Parity harness for the round-2 Qwen native setups (engine/qwen_natives.py): jeffan27, cerno, d3u and wemm (family d3). Same file formats, set specs, `compare` and gates as bench/qwen38_parity.py (rows {"id", "src", "keys", "probs", "n_tokens"} or {"id", "unsupported"}); every P300 item is a one-question request, so the request-level rules (d3-ultra's header and per-request temperature, Cerno's read-twice estimate) are applied per item exactly as the author engines apply them to such a request. ref REFERENCE arm, our re-implementation of the author's serving on stock libraries (no author code is imported or run): jeffan27 transformers Qwen3_5ForCausalLM (sdpa), bf16 under torch.autocast as jeffan_engine/modeling_jeffan decide(): model.model(ids, attention_mask={"full_attention": all-True [1,1,L,L], "linear_attention": None}, use_cache=False).last_hidden_state[0, -1] -> fp32 @ lm_head rows of the codes -> softmax, T=1 d3u/wemm transformers Qwen3_5Model (text tower, sdpa, bf16): language_model(ids, attention_mask={"full_attention": M, "linear_attention": None}) with M = prefix_bidir block mask (d3u) or all-True (wemm); last hidden state in fp32 @ readout.safetensors.T / T -> softmax (d3_runtime numerics: BF16 backbone, FP32 readout) cerno --arm vllm: stock vLLM (pin 0.31.0, as the author's requirements-27b-v1.1.txt) LLM(dtype=bfloat16, max_model_len=20480, max_logprobs=300, enable_prefix_caching=True), SamplingParams(max_tokens=1, temperature=0, logprobs=300) on our CernoTemplate rows, p = exp(logprob) of the labels (0 outside the top 300), renormalised, p^(1/1.059) (= engine_vllm.VllmEngine._run) --dtype float32 (jeffan27, d3u, wemm, cerno) = the fp32 adjudication arm: the whole model in fp32 with CPU offload (device_map=auto); for cerno the FP8 weights are dequantized (q * scale, fp32) into a stock Qwen3_5ForCausalLM. reax REAX arm: engine.registry.build() in process, c1 (one decision per step). compare / report: bench/qwen38_parity.py. """ from __future__ import annotations import argparse import json import math import sys import time from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from bench import qwen38_parity as Q # noqa: E402 from engine import d3_contract, qwen_natives as N # noqa: E402 SETUPS = {"jeffan27": "jeffan-27b-1211", "cerno": "cerno-27b-v1.1", "d3u": "d3-ultra", "wemm": "wemm-jev-27b"} # ---------------------------------------------------------------------------------------------- prompts (stdlib + tokenizer) class Renderer: """item -> (keys, ids, extra) for one setup; extra = {"state_block", "temperature"} where needed. ValueError = unsupported.""" def __init__(self, setup: str, tok, model_dir: str, max_input_tokens: int | None = None): self.setup, self.tok = setup, tok d = Path(model_dir) if setup == "jeffan27": self.t = N.Jeffan27Template(tok, max_input_tokens or N.JEFFAN27_MAX_LEN) self.code_ids, self.temperature = self.t.code_ids, 1.0 elif setup == "cerno": cfg = json.loads((d / "decider_config.json").read_text()) self.t = N.CernoTemplate(tok, cfg) self.code_ids, self.temperature = self.t.label_ids, self.t.temperature elif setup == "d3u": dc = json.loads((d / "decision_config.json").read_text()) self.t = N.D3UTemplate(tok, dc) self.code_ids = dc["token_ids"] elif setup == "wemm": dc = json.loads((d / "decision_config.json").read_text()) assert dc["attention_mode"] == "noncausal_full_attention" and dc.get("prompt_layout") is None self.codes, self.code_ids, self.temperature = dc["codes"], dc["token_ids"], float(dc["temperature"]) else: raise ValueError(setup) self.cap = max_input_tokens def __call__(self, state, question): if self.setup == "jeffan27": ids, _ = self.t.encode(state, question) keys, extra = self.t.options(question), {"temperature": 1.0} elif self.setup == "cerno": rows, info = self.t.encode_request(state, {"q": question}) ids, _ = rows["q"] keys, extra = self.t.options(question), {"temperature": self.temperature, "read_twice": info["read_twice"]} elif self.setup == "d3u": rows, info = self.t.encode_request(state, {"q": question}) ids, _, sb = rows["q"] keys, extra = self.t.options(question), {"temperature": info["temperature"], "state_block": sb} else: n = d3_contract.normalize_question(question) ids = self.tok(d3_contract.render(self.tok, state, n.rendered, self.codes), add_special_tokens=False)["input_ids"] keys, extra = n.keys, {"temperature": self.temperature} if self.cap and len(ids) > self.cap: raise ValueError(f"maximum context length exceeded: {len(ids)} > {self.cap} tokens") return keys, ids, extra def prefix_bidir_mask(n: int, sb: int): """bool [n, n]: state rows (i < sb) see the state block only, question rows see every token (d3_runtime prefix_bidir).""" import torch m = torch.ones(n, n, dtype=torch.bool) m[:sb, sb:] = False return m # ---------------------------------------------------------------------------------------------- reference arms def load_ref(setup, model_dir, dtype, device): import torch import transformers dt = torch.float32 if dtype == "float32" else torch.bfloat16 kw = {"attn_implementation": "sdpa", "dtype": dt} if dtype == "float32" and device != "cpu": kw.update(device_map="auto", max_memory={0: "86GiB", "cpu": "200GiB"}, offload_folder="/workspace/offload") elif device != "cpu": kw["device_map"] = {"": device} tok = transformers.AutoTokenizer.from_pretrained(model_dir) if setup == "jeffan27": model = transformers.AutoModelForCausalLM.from_pretrained(model_dir, **kw).eval() # native class (auto_map is AutoModel only) return model, tok, None if setup in ("d3u", "wemm"): from safetensors.torch import load_file model = transformers.Qwen3_5Model.from_pretrained(model_dir, **kw).eval() readout = load_file(str(Path(model_dir) / "readout.safetensors"))["weight"].float() return model, tok, readout if setup == "cerno": return load_cerno_dequant(model_dir, dt, kw), tok, None raise ValueError(setup) def load_cerno_dequant(model_dir, dt, kw): """Stock Qwen3_5ForCausalLM with the FP8 weights dequantized (q.float() * scale) in `dt` (the fp32 adjudication arm).""" import torch import transformers from safetensors import safe_open cfg = transformers.AutoConfig.from_pretrained(model_dir) if hasattr(cfg, "quantization_config"): del cfg.quantization_config with torch.device("meta"): model = transformers.Qwen3_5ForCausalLM(cfg) sd = {} idx = json.loads((Path(model_dir) / "model.safetensors.index.json").read_text())["weight_map"] for f in sorted(set(idx.values())): with safe_open(str(Path(model_dir) / f), framework="pt", device="cpu") as sf: for k in sf.keys(): if k.endswith(".weight_scale"): continue t = sf.get_tensor(k) if t.dtype == torch.float8_e4m3fn: t = t.float() * sf.get_tensor(k + "_scale").float() sd[k.replace("model.language_model.", "model.")] = t.to(dt) missing, unexpected = model.load_state_dict(sd, strict=False, assign=True) assert not [m for m in missing if "mtp" not in m] and not unexpected, (missing[:5], unexpected[:5]) from accelerate import dispatch_model, infer_auto_device_map dm = infer_auto_device_map(model, max_memory=kw.get("max_memory") or {0: "90GiB", "cpu": "200GiB"}, no_split_module_classes=["Qwen3_5DecoderLayer"]) if kw.get("device_map") is not None else None return (dispatch_model(model, dm) if dm else model).eval() def ref_logits(setup, model, readout, ids, extra, dtype, device): """Readout logits (fp32 list over the codes, before temperature) of one prompt.""" import torch first = next(model.parameters()).device if device != "cpu" else torch.device("cpu") x = torch.tensor([ids], device=first) n = len(ids) ac = torch.autocast("cuda", dtype=torch.bfloat16) if (setup == "jeffan27" and dtype == "bfloat16" and first.type == "cuda") \ else torch.autocast("cpu", enabled=False) with torch.inference_mode(), ac: if setup == "jeffan27": full = torch.ones(1, 1, n, n, dtype=torch.bool, device=first) h = model.model(input_ids=x, attention_mask={"full_attention": full, "linear_attention": None}, use_cache=False).last_hidden_state[0, -1] rows = model.lm_head.weight[torch.tensor(extra["code_ids"], device=model.lm_head.weight.device)] return (rows.float() @ h.float().to(rows.device)).tolist() if setup in ("d3u", "wemm"): m = prefix_bidir_mask(n, extra["state_block"]) if setup == "d3u" else torch.ones(n, n, dtype=torch.bool) h = model.language_model(input_ids=x, attention_mask={"full_attention": m[None, None].to(first), "linear_attention": None}, use_cache=False).last_hidden_state[0, -1] return (h.float().cpu() @ readout.T).tolist() # cerno fp32 arm: plain causal LM, logits of the labels at the last position, top-300 cut over the whole vocabulary lg = model(input_ids=x, logits_to_keep=1).logits[0, -1].float() kth = lg.topk(N.CERNO_TOPK).values[-1] sel = lg[torch.tensor(extra["code_ids"], device=lg.device)] return sel.masked_fill(sel < kth, -1e8).tolist() def softmax_t(logits, n, t): return Q.restricted_softmax(logits, n, temperature=t) def run_ref(a): t0 = time.time() Path(a.out_dir).mkdir(parents=True, exist_ok=True) info = {"entries": {}} if a.setup == "cerno" and a.arm == "vllm": return run_ref_vllm(a, t0, info) model, tok, readout = load_ref(a.setup, a.model, a.dtype, a.device) r = Renderer(a.setup, tok, a.model, a.max_input_tokens) info["load_seconds"] = round(time.time() - t0, 1) for spec in a.sets.split(","): items, rows, t1 = Q.load_items(spec, a.data_dir), [], time.time() for it in items: try: keys, ids, extra = r(it.state, it.question) except ValueError as exc: rows.append({"id": it.key, "unsupported": str(exc)}) continue extra["code_ids"] = r.code_ids lg = ref_logits(a.setup, model, readout, ids, extra, a.dtype, a.device) rows.append({"id": it.key, "src": it.src, "keys": keys, "n_tokens": len(ids), "probs": softmax_t(lg, len(keys), extra.get("temperature", 1.0))}) out = Path(a.out_dir, f"{a.tag}-{Q.spec_label(spec)}.jsonl") Q.write_rows(out, rows) info["entries"][spec] = {"file": out.name, "items": len(items), "seconds": round(time.time() - t1, 1)} print(f"ref {a.setup} {spec}: {len(rows)} rows in {time.time() - t1:.0f}s -> {out}", flush=True) Q.write_meta(a, t0, info) def run_ref_vllm(a, t0, info): """Cerno on stock vLLM exactly as engine_vllm.VllmEngine (author logic, our renderer; no author code).""" from transformers import AutoTokenizer from vllm import LLM, SamplingParams llm = LLM(model=a.model, dtype="bfloat16", max_model_len=N.CERNO_MAX_MODEL_LEN, max_logprobs=300, gpu_memory_utilization=0.9, enable_prefix_caching=True) sp = SamplingParams(max_tokens=1, temperature=0.0, logprobs=300) tok = AutoTokenizer.from_pretrained(a.model) r = Renderer("cerno", tok, a.model, a.max_input_tokens) info["load_seconds"] = round(time.time() - t0, 1) for spec in a.sets.split(","): items, rows, t1 = Q.load_items(spec, a.data_dir), [], time.time() for it in items: # one request at a time (the DI's sequential runner); one row per one-question request try: keys, ids, extra = r(it.state, it.question) except ValueError as exc: rows.append({"id": it.key, "unsupported": str(exc)}) continue out = llm.generate([{"prompt_token_ids": ids}], sp, use_tqdm=False)[0] lp = out.outputs[0].logprobs[0] if out.outputs and out.outputs[0].logprobs else {} n = len(keys) p = [math.exp(lp[t].logprob) if t in lp else 0.0 for t in r.code_ids[:n]] T = r.temperature if T != 1.0: p = [x ** (1.0 / T) if x > 0 else 0.0 for x in p] s = sum(p) rows.append({"id": it.key, "src": it.src, "keys": keys, "n_tokens": len(ids), "probs": [x / s for x in p] if s > 0 else [1.0 / n] * n, "read_twice": extra["read_twice"]}) outp = Path(a.out_dir, f"{a.tag}-{Q.spec_label(spec)}.jsonl") Q.write_rows(outp, rows) info["entries"][spec] = {"file": outp.name, "items": len(items), "seconds": round(time.time() - t1, 1)} print(f"ref cerno vllm {spec}: {len(rows)} rows in {time.time() - t1:.0f}s -> {outp}", flush=True) import vllm info["vllm"] = vllm.__version__ Q.write_meta(a, t0, info) # ---------------------------------------------------------------------------------------------- REAX arm def run_reax(a): import torch from engine import registry t0 = time.time() Path(a.out_dir).mkdir(parents=True, exist_ok=True) opts = {"warm_steps": a.warm_steps, **Q.parse_opts(a.opt)} if a.linear: opts["linear"] = a.linear if a.max_input_tokens: opts["max_input_tokens"] = a.max_input_tokens be = registry.build(SETUPS[a.setup], a.model, **opts) info = {"load_seconds": round(time.time() - t0, 1), "opts": opts, "entries": {}} for spec in a.sets.split(","): items = Q.load_items(spec, a.data_dir) for rep in range(1, a.repeat + 1): rows, st = Q.reax_rows(be, items, "c1", 1, torch.cuda.synchronize) out = Path(a.out_dir, f"{a.tag}-c1-{Q.spec_label(spec)}{'' if rep == 1 else f'-r{rep}'}.jsonl") Q.write_rows(out, rows) info["entries"][out.stem] = {"file": out.name, **st} print(f"reax {a.setup} c1 {spec} r{rep}: {st['decisions']} decisions, {st['decisions_per_s']}/s -> {out}", flush=True) Q.write_meta(a, t0, info) def run_longprobe(a): """Peak GPU memory and time of one decision at each requested prompt length (synthetic state, c1), engine arm only.""" import torch from engine import registry opts = {"warm_steps": 0, **Q.parse_opts(a.opt)} be = registry.build(SETUPS[a.setup], a.model, **opts) out = [] q = {"type": "noul", "instructions": "Does the text mention a red door?"} for n in [int(x) for x in a.lengths.split(",")]: state = ("The quick brown fox jumps over the lazy dog near the old mill. " * (n // 13 + 1)) enc = be.encode(state, q) while enc.n_tokens > n: # trim to the target length (prompt tokens incl. template) state = state[: int(len(state) * n / enc.n_tokens) - 8] enc = be.encode(state, q) torch.cuda.synchronize() torch.cuda.reset_peak_memory_stats() t = time.time() try: p = be.run([enc])[0] torch.cuda.synchronize() rec = {"target": n, "tokens": enc.n_tokens, "seconds": round(time.time() - t, 2), "probs": p, "peak_alloc_gib": round(torch.cuda.max_memory_allocated() / 2**30, 2)} except Exception as exc: # noqa: BLE001 (OOM is the finding) rec = {"target": n, "tokens": enc.n_tokens, "error": f"{type(exc).__name__}: {exc}"[:300]} torch.cuda.empty_cache() out.append(rec) print(json.dumps(rec), flush=True) Path(a.out_dir).mkdir(parents=True, exist_ok=True) Path(a.out_dir, f"{a.tag}.json").write_text(json.dumps(out, indent=1)) def main(argv=None): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = ap.add_subparsers(dest="cmd", required=True) for name in ("ref", "reax"): p = sub.add_parser(name) p.add_argument("--setup", choices=sorted(SETUPS), required=True) p.add_argument("--model", required=True) p.add_argument("--sets", default="p300") p.add_argument("--out-dir", required=True) p.add_argument("--tag", required=True) p.add_argument("--max-input-tokens", type=int, default=0, help="0 = the setup's own limit") p.add_argument("--data-dir", default=None) if name == "ref": p.add_argument("--dtype", choices=("bfloat16", "float32"), default="bfloat16") p.add_argument("--arm", choices=("hf", "vllm"), default="hf", help="cerno: vllm = the author's serving stack") p.add_argument("--device", default="cuda") p.set_defaults(fn=run_ref) else: p.add_argument("--linear", choices=("fp8", "bf16"), default=None, help="default: the registry factory's (fp8 for cerno, bf16 else)") p.add_argument("--warm-steps", type=int, default=0) p.add_argument("--repeat", type=int, default=1) p.add_argument("--opt", action="append") p.set_defaults(fn=run_reax) lp = sub.add_parser("longprobe", help="engine: peak GPU memory / time of one decision per prompt length") lp.add_argument("--setup", choices=sorted(SETUPS), required=True) lp.add_argument("--model", required=True) lp.add_argument("--out-dir", required=True) lp.add_argument("--tag", required=True) lp.add_argument("--lengths", required=True, help="comma list of prompt lengths in tokens, e.g. 8192,32768,65536") lp.add_argument("--opt", action="append") lp.set_defaults(fn=run_longprobe) c = sub.add_parser("compare") c.add_argument("ref") c.add_argument("cand") c.add_argument("--set", default=None) c.add_argument("--out", default=None) c.add_argument("--data-dir", default=None) c.set_defaults(fn=Q.run_compare) a = ap.parse_args(argv) if getattr(a, "max_input_tokens", None) == 0: a.max_input_tokens = None return a.fn(a) if __name__ == "__main__": sys.exit(main())