Upload scripts/peer/peer_run.py with huggingface_hub
Browse files- scripts/peer/peer_run.py +140 -0
scripts/peer/peer_run.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
peer_run.py -- generate completions for peer-model NIAH prompts.
|
| 4 |
+
|
| 5 |
+
Backends, tried in this order unless --backend forces one:
|
| 6 |
+
vllm fast, batched. Cannot load Spark-X2.5 (model_type spark2_5 is
|
| 7 |
+
custom_code and has no vLLM backend), so it is skipped automatically.
|
| 8 |
+
hf transformers with trust_remote_code. Works for everything, slower.
|
| 9 |
+
|
| 10 |
+
Prompts are fed as TOKEN IDS, never text: peer_gen.py guarantees an exact token
|
| 11 |
+
count and a decode->re-encode round trip would silently break it.
|
| 12 |
+
|
| 13 |
+
Greedy decoding, matching our own harness (CP_GEN_GREEDY=1). Generation stops at
|
| 14 |
+
--max-new tokens; no early stop, because the peer models have no shared
|
| 15 |
+
end-of-answer convention and truncation is harmless -- scoring is substring
|
| 16 |
+
match, so trailing chatter costs nothing.
|
| 17 |
+
|
| 18 |
+
usage:
|
| 19 |
+
peer_run.py --model Qwen/Qwen3-4B-Base --prompts out/niah_single_prompts.jsonl \
|
| 20 |
+
--out gen/qwen3-4b_niah_single.jsonl --max-new 24
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import json
|
| 25 |
+
import os
|
| 26 |
+
import sys
|
| 27 |
+
import time
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def load_prompts(p):
|
| 31 |
+
rows = []
|
| 32 |
+
with open(p) as f:
|
| 33 |
+
for line in f:
|
| 34 |
+
line = line.strip()
|
| 35 |
+
if line:
|
| 36 |
+
rows.append(json.loads(line))
|
| 37 |
+
return rows
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def run_vllm(model, rows, max_new, gpu_frac, max_len):
|
| 41 |
+
from vllm import LLM, SamplingParams
|
| 42 |
+
llm = LLM(model=model, dtype="bfloat16", trust_remote_code=True,
|
| 43 |
+
gpu_memory_utilization=gpu_frac, max_model_len=max_len,
|
| 44 |
+
enforce_eager=False)
|
| 45 |
+
sp = SamplingParams(temperature=0.0, max_tokens=max_new)
|
| 46 |
+
outs = llm.generate(prompt_token_ids=[r["ids"] for r in rows],
|
| 47 |
+
sampling_params=sp)
|
| 48 |
+
return [o.outputs[0].text for o in outs]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def run_hf(model, rows, max_new, batch):
|
| 52 |
+
import torch
|
| 53 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 54 |
+
tok = AutoTokenizer.from_pretrained(model, trust_remote_code=True)
|
| 55 |
+
m = AutoModelForCausalLM.from_pretrained(
|
| 56 |
+
model, dtype=torch.bfloat16, device_map="cuda", trust_remote_code=True)
|
| 57 |
+
m.eval()
|
| 58 |
+
texts = []
|
| 59 |
+
# batch=1 by default: these are 16k-token prompts and padding a ragged batch
|
| 60 |
+
# would change each sequence's positions, which is exactly what NIAH measures.
|
| 61 |
+
for s in range(0, len(rows), batch):
|
| 62 |
+
chunk = rows[s:s + batch]
|
| 63 |
+
ids = torch.tensor([r["ids"] for r in chunk], device="cuda")
|
| 64 |
+
with torch.no_grad():
|
| 65 |
+
out = m.generate(input_ids=ids, max_new_tokens=max_new,
|
| 66 |
+
do_sample=False, num_beams=1,
|
| 67 |
+
pad_token_id=getattr(tok, "pad_token_id", None)
|
| 68 |
+
or getattr(tok, "eos_token_id", 0))
|
| 69 |
+
for j in range(len(chunk)):
|
| 70 |
+
texts.append(tok.decode(out[j][ids.shape[1]:], skip_special_tokens=True))
|
| 71 |
+
done = min(s + batch, len(rows))
|
| 72 |
+
print(f" {done}/{len(rows)}", flush=True)
|
| 73 |
+
return texts
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def main():
|
| 77 |
+
ap = argparse.ArgumentParser()
|
| 78 |
+
ap.add_argument("--model", required=True)
|
| 79 |
+
ap.add_argument("--prompts", required=True)
|
| 80 |
+
ap.add_argument("--out", required=True)
|
| 81 |
+
ap.add_argument("--max-new", type=int, default=24)
|
| 82 |
+
ap.add_argument("--backend", default="auto", choices=["auto", "vllm", "hf"])
|
| 83 |
+
ap.add_argument("--gpu-frac", type=float, default=0.90)
|
| 84 |
+
ap.add_argument("--batch", type=int, default=1, help="hf backend only")
|
| 85 |
+
args = ap.parse_args()
|
| 86 |
+
|
| 87 |
+
rows = load_prompts(args.prompts)
|
| 88 |
+
if not rows:
|
| 89 |
+
sys.exit(f"no prompts in {args.prompts}")
|
| 90 |
+
plen = len(rows[0]["ids"])
|
| 91 |
+
max_len = plen + args.max_new + 8
|
| 92 |
+
# Never ask vLLM for more than the checkpoint's trained window: Qwen3-Base
|
| 93 |
+
# ships max_position_embeddings=32768, so a 32,744-token prompt + 24 new + 8
|
| 94 |
+
# slack would exceed it and vLLM refuses to start. Clamp, and say so.
|
| 95 |
+
try:
|
| 96 |
+
from transformers import AutoConfig
|
| 97 |
+
mp = getattr(AutoConfig.from_pretrained(args.model, trust_remote_code=True),
|
| 98 |
+
"max_position_embeddings", None)
|
| 99 |
+
if mp and max_len > mp:
|
| 100 |
+
print(f" clamping max_model_len {max_len} -> {mp} (model's native window)")
|
| 101 |
+
max_len = mp
|
| 102 |
+
if plen + args.max_new > mp:
|
| 103 |
+
sys.exit(f" FATAL: prompt {plen} + max_new {args.max_new} exceeds "
|
| 104 |
+
f"the model's window {mp}; lower --prompt-len")
|
| 105 |
+
except Exception as e:
|
| 106 |
+
print(f" (could not read max_position_embeddings: {type(e).__name__})")
|
| 107 |
+
print(f" {args.model} {len(rows)} prompts x {plen} tok max_new={args.max_new}")
|
| 108 |
+
|
| 109 |
+
backend = args.backend
|
| 110 |
+
if backend == "auto":
|
| 111 |
+
backend = "hf"
|
| 112 |
+
try:
|
| 113 |
+
import vllm # noqa: F401
|
| 114 |
+
# spark2_5 is custom_code with no vLLM backend; do not waste a load
|
| 115 |
+
backend = "hf" if "spark" in args.model.lower() else "vllm"
|
| 116 |
+
except ImportError:
|
| 117 |
+
pass
|
| 118 |
+
print(f" backend: {backend}")
|
| 119 |
+
|
| 120 |
+
t0 = time.time()
|
| 121 |
+
if backend == "vllm":
|
| 122 |
+
try:
|
| 123 |
+
texts = run_vllm(args.model, rows, args.max_new, args.gpu_frac, max_len)
|
| 124 |
+
except Exception as e:
|
| 125 |
+
print(f" vLLM failed ({type(e).__name__}: {str(e)[:140]}) -- falling back to hf")
|
| 126 |
+
texts = run_hf(args.model, rows, args.max_new, args.batch)
|
| 127 |
+
else:
|
| 128 |
+
texts = run_hf(args.model, rows, args.max_new, args.batch)
|
| 129 |
+
dt = time.time() - t0
|
| 130 |
+
|
| 131 |
+
os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True)
|
| 132 |
+
with open(args.out, "w") as f:
|
| 133 |
+
for r, t in zip(rows, texts):
|
| 134 |
+
f.write(json.dumps({"i": r["i"], "generated": t}) + "\n")
|
| 135 |
+
print(f" wrote {args.out} ({len(texts)} rows, {dt:.0f}s, "
|
| 136 |
+
f"{dt/max(1,len(texts)):.2f}s/prompt)")
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
if __name__ == "__main__":
|
| 140 |
+
main()
|