1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
| """JEV front door on top of sglang.
Same host port serves both systems (per JEV deployment goal): POST /v1/decide System 1 (LoRA "jev-decision" + decision head) with adaptive System 2 thinking * (everything else) transparent proxy to sglang (System 2 native: /v1/chat/completions, /generate, ...)
Read-out path: sglang /generate with token_ids_logprob (exact token logprobs at the first output position). Fallback: top_logprobs_num=300 if token_ids_logprob comes back empty (e.g. speculative-decoding path limitations). """ import json import math import os import string import time import zlib from typing import Literal, Optional, Union
import httpx from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, Response, StreamingResponse from pydantic import BaseModel
NL = chr(10)
UPSTREAM = os.environ.get("UPSTREAM", "http://127.0.0.1:30100") LORA = os.environ.get("JEV_DECIDE_LORA", "jev-decision") MODEL_DIR = os.environ.get("MODEL_DIR", "/models/Qwen3.8-27B-FP8") ADAPTER_DIR = os.environ.get("ADAPTER_DIR", "/models/JEV-27B-VL-adapter/adapter_vllm") PROTOCOL = "jev27-bare-v1" PLACEHOLDER = "XQXCONTENTXQX" MAX_OPTIONS = 256 FALLBACK_TOPK = 300 S2_DEFAULT_BUDGET = 32768
_TH = chr(60) + "think" + chr(62) T_END = chr(60) + "/think" + chr(62) THINK_OPEN = chr(10) + _TH THINK_CLOSE = chr(10) + T_END
IMG_TOKEN = "<|" + "vision_start" + "|>" + "<|" + "image_pad" + "|>" + "<|" + "vision_end" + "|>"
PROF = { "prefix": "", "image": IMG_TOKEN, "end_think": THINK_CLOSE, "after_think": NL + NL, "strategy": "single", "threshold": 0.8, "mix": 0.5, "thinking": "off", } for k in ("strategy", "threshold", "mix", "thinking"): env = os.environ.get("JEV_DECIDE_" + k.upper()) if env: PROF[k] = env if k in ("strategy", "thinking") else float(env)
head = json.load(open(os.path.join(ADAPTER_DIR, "decision_head.json"))) _calib = os.environ.get("JEV_DECIDE_CALIBRATION") or os.path.join( os.path.dirname(os.path.abspath(ADAPTER_DIR)), "calibration.json") temps = json.load(open(_calib))["per_kind"] if os.path.exists(_calib) else {"noul": 1.0, "score": 1.0, "choice": 1.0} temps.setdefault("score", 1.0)
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained(MODEL_DIR, trust_remote_code=True) has_effort = "reasoning_effort" in (tok.chat_template or "")
def single_token_labels(context): out = [] for lab in list(string.ascii_uppercase) + [a + b for a in string.ascii_uppercase for b in string.ascii_uppercase]: t = tok.encode(lab, add_special_tokens=False) if len(t) == 1 and t[0] in tok.encode(context.format(lab), add_special_tokens=False): out.append((lab, t[0])) if len(out) == MAX_OPTIONS: break return out
dec = single_token_labels("x" + NL + chr(123) + chr(125) + ") y") _clo, _chi = head["slots"]["ranges"]["choice"] assert [t for _, t in dec[: _chi - _clo]] == head["verbalizer_ids"][_clo:_chi], \ "first labels must be the trained A-P head" labels = [l for l, _ in dec] label_ids = [t for _, t in dec]
_base = tok.encode("Answer: (", add_special_tokens=False) ans = [] for lab in list(string.ascii_uppercase) + [a + b for a in string.ascii_uppercase for b in string.ascii_uppercase]: ids = tok.encode("Answer: (" + lab + ")", add_special_tokens=False) if ids[: len(_base)] == _base and len(ids) == len(_base) + 2: ans.append((lab, ids[len(_base)])) if len(ans) == MAX_OPTIONS: break ans_labels = ans
_think_cache = {}
def _think_frame(kwargs): key = json.dumps(kwargs or {}, sort_keys=True) if key not in _think_cache: kw = {k: v for k, v in (kwargs or {}).items() if k != "enable_thinking"} chat = tok.apply_chat_template( [{"role": "user", "content": PLACEHOLDER}], tokenize=False, add_generation_prompt=True, enable_thinking=True, **kw) _think_cache[key] = tuple(chat.split(PLACEHOLDER)) return _think_cache[key]
def _parts(state): if isinstance(state, str): return [{"type": "text", "text": state}], False if isinstance(state, dict): return [{"type": "text", "text": json.dumps(state, ensure_ascii=False)}], False out, img = [], False for p in state: if isinstance(p, str): out.append({"type": "text", "text": p}) elif isinstance(p, dict) and "image" in p: out.append({"type": "image_url", "image_url": {"url": p["image"]}}) img = True elif isinstance(p, dict) and p.get("type") == "image_url": out.append(p) img = True elif isinstance(p, dict) and p.get("type") == "text": out.append(p) else: out.append({"type": "text", "text": json.dumps(p, ensure_ascii=False)}) return out, img
def _render(parts): """Render content parts to (text, image_data). Image parts render to the image placeholder; urls kept in order.""" text, image_data = "", [] for p in parts: if p.get("type") == "image_url": text += PROF["image"] image_data.append(p["image_url"]["url"]) else: text += p.get("text", "") return text, image_data
def _softmax(z): m = max(z) e = [math.exp(x - m) for x in z] s = sum(e) return [x / s for x in e]
class UpstreamError(Exception): def __init__(self, status, detail): self.status, self.detail = status, detail
class Ctx: def __init__(self): self.requests = 0 self.prompt_tokens = 0 self.completion_tokens = 0
def count(self, meta): self.requests += 1 self.prompt_tokens += int(meta.get("prompt_tokens") or 0) self.completion_tokens += int(meta.get("completion_tokens") or 0)
app = FastAPI() client = httpx.AsyncClient(timeout=httpx.Timeout(900.0, connect=10.0), limits=httpx.Limits(max_connections=100, max_keepalive_connections=50))
def _parse_logprob_entry(e): """sglang /generate logprob entries are [logprob, token_id, text?] lists or dicts.""" if isinstance(e, dict): tid = e.get("id", e.get("token_id")) if tid is None: t = e.get("text") or "" tid = tok.convert_tokens_to_ids(t) if t else None return int(tid), float(e["logprob"]) return int(e[1]), float(e[0])
async def _read_logprobs(ctx, text, ids, lora_id, image_data): """One-token read-out: {token_id: logprob} at the first output position.""" body = { "text": text, "sampling_params": {"max_new_tokens": 1, "temperature": 1.0, "top_p": 1.0, "top_k": -1, "min_p": 0.0, "repetition_penalty": 1.0}, "return_logprob": True, "token_ids_logprob": ids, } if lora_id: body["lora_path"] = lora_id if image_data: body["image_data"] = image_data r = await client.post(UPSTREAM + "/generate", json=body) if r.status_code != 200: raise UpstreamError(r.status_code, r.text[:500]) meta = r.json()["meta_info"] ctx.count(meta) out = {} ot = meta.get("output_token_ids_logprobs") or [] if ot: for e in ot[0] or []: if e is None: continue tid, lp = _parse_logprob_entry(e) out[tid] = lp if out: return out body2 = {k: v for k, v in body.items() if k != "token_ids_logprob"} body2["top_logprobs_num"] = FALLBACK_TOPK r2 = await client.post(UPSTREAM + "/generate", json=body2) if r2.status_code != 200: raise UpstreamError(r2.status_code, r2.text[:500]) meta2 = r2.json()["meta_info"] ctx.count(meta2) tl = meta2.get("output_top_logprobs") or [] for e in (tl[0] if tl else []): if e is None: continue tid, lp = _parse_logprob_entry(e) if tid in ids: out[tid] = lp return out
async def s1_pass(ctx, kind, parts, image_data, question, opts): lo, hi = head["slots"]["ranges"][kind] if kind == "choice": n = len(opts) ids = label_ids[:n] bias = [head["bias"][lo + i] if lo + i < hi else 0.0 for i in range(n)] lines = [labels[i] + ") " + o for i, o in enumerate(opts)] else: ids = head["verbalizer_ids"][lo:hi] bias = head["bias"][lo:hi] lines = opts text = (PROF["prefix"] + "[kind] " + kind + NL + "[state] " + _render(parts)[0] + NL + "[question] " + question + NL + "[options]" + NL + NL.join(lines) + NL + "[decision]:") lp = await _read_logprobs(ctx, text, ids, LORA, image_data) return _softmax([(max(lp.get(t, -1e9), -1e9) + b) / temps[kind] for t, b in zip(ids, bias)])
def _groups(n, k=16): g = math.ceil(n / k) base, extra = divmod(n, g) out, i = [], 0 for j in range(g): size = base + (1 if j < extra else 0) out.append(list(range(i, i + size))) i += size return out
async def s1_dist(ctx, kind, parts, image_data, question, opts, strategy): if kind != "choice" or len(opts) <= 16 or strategy == "single": return await s1_pass(ctx, kind, parts, image_data, question, opts) n = len(opts) if strategy == "permute": import random rng = random.Random(zlib.crc32(question.encode())) orders = [list(range(n))] + [rng.sample(range(n), n) for _ in range(3)] res = [await s1_pass(ctx, kind, parts, image_data, question, [opts[i] for i in o]) for o in orders] p = [0.0] * n for o, r in zip(orders, res): for i, v in zip(o, r): p[i] += v / len(orders) return p groups = _groups(n) parts_g = [await s1_pass(ctx, kind, parts, image_data, question, [opts[i] for i in g]) for g in groups] in_group = {o: p for g, ps in zip(groups, parts_g) for o, p in zip(g, ps)} chosen = [max(g, key=lambda o: (in_group[o], -o)) for g in groups] rest = sorted((o for g in groups for o in g if o not in set(chosen)), key=lambda o: (-in_group[o], o)) fin = sorted(chosen + rest[: max(0, 16 - len(chosen))]) final = dict(zip(fin, await s1_pass(ctx, kind, parts, image_data, question, [opts[i] for i in fin]))) group_of = {o: gi for gi, g in enumerate(groups) for o in g} share = [0.0] * len(groups) cap = [0.0] * len(groups) for f in fin: share[group_of[f]] += final[f] cap[group_of[f]] += in_group[f] among = sum(a * b for a, b in zip(share, cap)) p = [final[o] * among if o in final else share[group_of[o]] * in_group[o] for o in range(n)] s = sum(p) return [x / s for x in p]
async def s2_dist(ctx, kind, parts, image_data, question, opts, budget, want_text, tmpl_kwargs): shown = ["Yes (true)", "No (false)"] if kind == "noul" else opts labs = ans_labels[: len(shown)] body = NL.join("(" + l + ") " + o for (l, _), o in zip(labs, shown)) tail = (NL + NL + "Question: " + question + NL + NL + "Options:" + NL + body + NL + NL + "Think it through carefully, then give your final answer on the last line in the form: Answer: (X)") pre, post = _think_frame(tmpl_kwargs) gen_parts = [{"type": "text", "text": pre}] + parts + [{"type": "text", "text": tail + post}] gen_text, gen_imgs = _render(gen_parts) t0 = time.time() body = { "text": gen_text, "sampling_params": {"max_new_tokens": budget or S2_DEFAULT_BUDGET, "stop": [THINK_CLOSE], "temperature": 1.0}, } if gen_imgs: body["image_data"] = gen_imgs r = await client.post(UPSTREAM + "/generate", json=body) if r.status_code != 200: raise UpstreamError(r.status_code, r.text[:500]) data = r.json() thought = data.get("text") or "" meta = data.get("meta_info", {}) ctx.count(meta) finished = meta.get("finish_reason") in ("stop", None) idx = thought.find(THINK_CLOSE) if idx != -1: thought = thought[:idx] ntok = meta.get("completion_tokens") read_text, read_imgs = _render([{"type": "text", "text": pre}] + parts + [{"type": "text", "text": tail + post + thought + THINK_CLOSE + PROF["after_think"] + "Answer: ("}]) ids = [t for _, t in labs] lp = await _read_logprobs(ctx, read_text, ids, None, read_imgs) p = _softmax([max(lp.get(t, -1e9), -1e9) for t in ids]) if kind == "noul": p = [p[1], p[0]] info = {"think_tokens": ntok, "think_seconds": round(time.time() - t0, 3), "finished_within_budget": finished} if want_text: info["reasoning"] = thought.strip() return p, info
def _fold(p1, p2, w): return [(1 - w) * x + w * y for x, y in zip(p1, p2)]
class DecideRequest(BaseModel): kind: Literal["noul", "score", "choice"] state: Union[str, dict, list] = "" question: str options: Optional[list] = None strategy: Literal["auto", "single", "tournament", "permute"] = "auto" thinking: Literal["default", "off", "auto", "on"] = "default" threshold: Optional[float] = None think_budget: Optional[int] = None reasoning_effort: Optional[str] = None chat_template_kwargs: Optional[dict] = None return_reasoning: bool = False debug: bool = False system2_only: bool = False
def _err(msg, code=400): return JSONResponse({"error": {"message": msg, "type": "BadRequestError", "code": code}}, status_code=code)
@app.get("/v1/decide/info") async def decide_info(): return {"protocol": PROTOCOL, "model": MODEL_DIR, "max_options": len(labels), "native_choice_options": len(head["slots"]["verbalizers"]) - 8, "temperatures": temps, "defaults": {"strategy": PROF["strategy"], "thinking": PROF["thinking"], "threshold": PROF["threshold"], "mix": PROF["mix"], "think_budget": None}, "reasoning_controls": {"enable_thinking": True, "reasoning_effort": ["xhigh", "medium", "low"] if has_effort else None, "think_budget": "max thinking tokens (default: up to the context window)"}, "gate": ("thinking=auto: S2 fires when max(S1 prob) < threshold; " "a threshold <= 1/options is degenerate and is clamped to 1/options + 0.25 " "(see response thinking.threshold_effective)")}
@app.get("/health") async def health(): try: r = await client.get(UPSTREAM + "/health") ok = r.status_code == 200 except Exception: ok = False return JSONResponse({"front_door": "ok", "sglang": "ok" if ok else "down"}, status_code=200 if ok else 503)
@app.post("/v1/decide") async def decide(req: DecideRequest): t0 = time.time() if req.kind == "choice": opts = req.options or [] if not 2 <= len(opts) <= len(labels): return _err("choice needs 2-" + str(len(labels)) + " options, got " + str(len(opts))) else: opts = ["false", "true"] if req.kind == "noul" else [str(i) for i in range(6)] thinking = PROF["thinking"] if req.thinking == "default" else req.thinking tmpl = dict(req.chat_template_kwargs or {}) if req.reasoning_effort is not None: if not has_effort: return _err("this base model has no reasoning_effort setting; control the reasoning length with think_budget") tmpl["reasoning_effort"] = req.reasoning_effort strategy = PROF["strategy"] if req.strategy == "auto" else req.strategy tau = PROF["threshold"] if req.threshold is None else req.threshold _k = len(opts) if req.kind == "choice" else (2 if req.kind == "noul" else 6) tau_eff = tau if tau > 1.0 / _k else min(1.0, 1.0 / _k + 0.25) parts, has_img = _parts(req.state) text0, image_data = _render(parts) ctx = Ctx() try: if req.system2_only: p2, think = await s2_dist(ctx, req.kind, parts, image_data, req.question, opts, req.think_budget, req.return_reasoning, tmpl) k = max(range(len(p2)), key=p2.__getitem__) return {"kind": req.kind, "options": opts, "probabilities": p2, "choice_index": k, "choice": opts[k], "system": 2, "model": MODEL_DIR, "thinking": {"used": True, "budget": req.think_budget, **think}, "usage": {"prompt_tokens": ctx.prompt_tokens, "completion_tokens": ctx.completion_tokens}, "elapsed_seconds": time.time() - t0, "num_model_requests": ctx.requests} p1 = await s1_dist(ctx, req.kind, parts, image_data, req.question, opts, strategy) probs, think = p1, None if thinking == "on" or (thinking == "auto" and max(p1) < tau_eff): p2, think = await s2_dist(ctx, req.kind, parts, image_data, req.question, opts, req.think_budget, req.return_reasoning, tmpl) probs = _fold(p1, p2, PROF["mix"]) think = {"used": True, **think} if req.debug: think.update(system1=p1, system2=p2) elif thinking != "off": think = {"used": False} if req.debug: think["system1"] = p1 except UpstreamError as e: return JSONResponse({"error": e.detail}, status_code=e.status) k = max(range(len(probs)), key=probs.__getitem__) native = req.kind != "choice" or len(opts) <= 16 resp = {"kind": req.kind, "effective_kind": req.kind, "options": opts, "probabilities": probs, "choice_index": k, "choice": opts[k], "adaptation": "native" if native else strategy, "protocol": PROTOCOL, "model": MODEL_DIR, "usage": {"prompt_tokens": ctx.prompt_tokens, "completion_tokens": ctx.completion_tokens, "total_tokens": ctx.prompt_tokens + ctx.completion_tokens}, "elapsed_seconds": time.time() - t0, "num_model_requests": ctx.requests} if think is not None: resp["thinking"] = {"mode": thinking, "threshold": tau, "threshold_effective": tau_eff, "budget": req.think_budget, **({"chat_template_kwargs": tmpl} if tmpl else {}), **think} return resp
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]) async def proxy(path: str, request: Request): url = UPSTREAM + "/" + path headers = {k: v for k, v in request.headers.items() if k.lower() not in ("host", "content-length")} body = await request.body() upstream_req = client.build_request(request.method, url, headers=headers, content=body, params=dict(request.query_params)) r = await client.send(upstream_req, stream=True) ctype = r.headers.get("content-type", "") hop = {"content-length", "transfer-encoding", "connection", "keep-alive"} rheaders = {k: v for k, v in r.headers.items() if k.lower() not in hop} if "text/event-stream" in ctype: async def gen(): try: async for chunk in r.aiter_bytes(): yield chunk finally: await r.aclose() return StreamingResponse(gen(), status_code=r.status_code, headers=rheaders) data = await r.aread() await r.aclose() return Response(content=data, status_code=r.status_code, headers=rheaders)
if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "30000")))
|