SargeDev commited on
Commit
205133e
·
verified ·
1 Parent(s): 48b9ad8

add serve_decide.py

Browse files
Files changed (1) hide show
  1. serve_decide.py +430 -0
serve_decide.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """vLLM OpenAI-compatible server with a built-in System 1 endpoint (POST /v1/decide) and adaptive thinking.
3
+
4
+ One engine serves both systems, for JEV-27B / JEV-27B-VL (Qwen3.8) and GEV-26B-A4B (Gemma-4):
5
+ System 2 the unmodified base model, through the usual OpenAI endpoints (served model name)
6
+ System 1 the LoRA module "jev-decision" (backbone LoRA + decision head as an lm_head LoRA), through /v1/decide
7
+
8
+ POST /v1/decide
9
+ kind "noul" (yes/no), "score" (0-5) or "choice" (2-256 options)
10
+ state string, JSON object, or a list mixing text and images: ["text", {"image": "https://... | data:..."}]
11
+ question string
12
+ options list of strings (choice only)
13
+ strategy choices with more than 16 options: "single" (one pass, labels A-P then Q-Z, AA, ...), "tournament"
14
+ (groups of <=16 + a final of 16), "permute" (single pass over 4 option orders, averaged); default per model
15
+ thinking "off" (default: System 1 only), "auto" (think only when the leading option is below `threshold`),
16
+ "on" (always think)
17
+ threshold System 1 confidence below which "auto" switches thinking on (default per model)
18
+ reasoning controls, as for the base model's own chat API:
19
+ chat_template_kwargs passed to the base model's chat template (e.g. Qwen3.8: {"reasoning_effort": "low"})
20
+ reasoning_effort shorthand for chat_template_kwargs.reasoning_effort, if the base model has it
21
+ (Qwen3.8 / JEV-27B: xhigh (default), medium, low; Gemma-4 / GEV: not available)
22
+ think_budget maximum thinking tokens; default: no limit beyond the context window
23
+ return_reasoning include System 2's reasoning text
24
+ debug include the System 1 and System 2 distributions
25
+
26
+ Adaptive thinking: System 1 gives p1 in one pass. If thinking is switched on, the base model reasons in its thinking
27
+ mode over the same state, question and options; when the thinking channel closes, the answer-letter distribution p2 is
28
+ read in one step, and the result is p = (1 - w) * p1 + w * p2 (default w = 0.5: the fast decision and the reasoning get
29
+ equal weight, which keeps the calibration of System 1; p2 alone is close to one-hot and over-confident).
30
+
31
+ Response (same shape as the hosted JEV API, plus "thinking" when requested):
32
+ {"kind", "effective_kind", "options", "probabilities", "choice_index", "choice", "adaptation", "protocol", "model",
33
+ "usage", "elapsed_seconds", "num_model_requests", "thinking": {...}}
34
+
35
+ Run it like `python -m vllm.entrypoints.openai.api_server` (same flags), with --lora-modules jev-decision=<adapter dir>
36
+ and --trust-request-chat-template. decision_head.json is read from the adapter directory, calibration.json from its
37
+ parent (override with JEV_DECIDE_CALIBRATION).
38
+ """
39
+ import asyncio
40
+ import json
41
+ import math
42
+ import os
43
+ import string
44
+ import time
45
+ import zlib
46
+ from typing import Literal
47
+
48
+ from fastapi import APIRouter, Request
49
+ from fastapi.responses import JSONResponse
50
+ from pydantic import BaseModel
51
+
52
+ import vllm.entrypoints.launchers.api_server.entry as entry
53
+ from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
54
+ from vllm.entrypoints.openai.completion.protocol import CompletionRequest
55
+
56
+ LORA = os.environ.get("JEV_DECIDE_LORA", "jev-decision")
57
+ MAX_OPTIONS = 256
58
+ CHUNK = 128 # vLLM caps logprob_token_ids at 128 per request
59
+ PROTOCOL = "jev27-bare-v1"
60
+ PLACEHOLDER = "XQXCONTENTXQX"
61
+
62
+ # Per-model settings. threshold / mix: adaptive-thinking defaults. GEV: fitted on 1,754 questions outside the Decision
63
+ # Index (CommonsenseQA, OpenBookQA, AQuA-RAT, MedMCQA, LogiQA, StrategyQA). JEV-27B: same defaults, not yet validated.
64
+ PROFILES = {
65
+ "qwen": {"prefix": "", "image": "<|vision_start|><|image_pad|><|vision_end|>", "end_think": "</think>",
66
+ "after_think": "\n\n", "strategy": "single", "threshold": 0.8, "mix": 0.5, "thinking": "off"},
67
+ "gemma": {"prefix": "<bos>", "image": "<|image|>", "end_think": "<channel|>", "after_think": "",
68
+ "strategy": "tournament", "threshold": 0.8, "mix": 0.5, "thinking": "off"},
69
+ }
70
+ # Read the full distribution: override generation_config defaults (top_k/top_p) that would truncate processed logprobs.
71
+ READ = dict(max_tokens=1, temperature=1.0, top_p=1.0, top_k=0, min_p=0.0, repetition_penalty=1.0,
72
+ add_special_tokens=False, return_tokens_as_token_ids=True)
73
+ S = {}
74
+
75
+
76
+ class DecideRequest(BaseModel):
77
+ kind: Literal["noul", "score", "choice"]
78
+ state: str | dict | list = ""
79
+ question: str
80
+ options: list[str] | None = None
81
+ strategy: Literal["auto", "single", "tournament", "permute"] = "auto"
82
+ thinking: Literal["default", "off", "auto", "on"] = "default"
83
+ threshold: float | None = None
84
+ think_budget: int | None = None
85
+ reasoning_effort: str | None = None
86
+ chat_template_kwargs: dict | None = None
87
+ return_reasoning: bool = False
88
+ debug: bool = False
89
+ system2_only: bool = False # skip System 1: think and return System 2's answer distribution (for callers that already have p1)
90
+
91
+
92
+ # ------------------------------------------------------------------ setup
93
+ def setup(args):
94
+ from transformers import AutoConfig, AutoTokenizer
95
+
96
+ path = next((m.path for m in (args.lora_modules or []) if m.name == LORA), None)
97
+ if path is None:
98
+ raise SystemExit(f"serve_decide: start vLLM with --lora-modules {LORA}=<adapter dir>")
99
+ head = json.load(open(os.path.join(path, "decision_head.json")))
100
+ calib = os.environ.get("JEV_DECIDE_CALIBRATION") or os.path.join(os.path.dirname(os.path.abspath(path)), "calibration.json")
101
+ temps = json.load(open(calib))["per_kind"] if os.path.exists(calib) else {"noul": 1.0, "score": 1.0, "choice": 1.0}
102
+ temps.setdefault("score", 1.0)
103
+ src = args.tokenizer or args.model
104
+ tok = AutoTokenizer.from_pretrained(src, trust_remote_code=args.trust_remote_code)
105
+ mtype = AutoConfig.from_pretrained(args.model, trust_remote_code=args.trust_remote_code).model_type
106
+ prof = dict(PROFILES["gemma" if "gemma" in mtype else "qwen"])
107
+ for k in ("strategy", "threshold", "mix", "thinking"):
108
+ if os.environ.get(f"JEV_DECIDE_{k.upper()}"):
109
+ v = os.environ[f"JEV_DECIDE_{k.upper()}"]
110
+ prof[k] = v if k in ("strategy", "thinking") else float(v)
111
+
112
+ def single_token_labels(context):
113
+ out = []
114
+ for lab in list(string.ascii_uppercase) + [a + b for a in string.ascii_uppercase for b in string.ascii_uppercase]:
115
+ t = tok.encode(lab, add_special_tokens=False)
116
+ if len(t) == 1 and t[0] in tok.encode(context.format(lab), add_special_tokens=False):
117
+ out.append((lab, t[0]))
118
+ if len(out) == MAX_OPTIONS:
119
+ break
120
+ return out
121
+
122
+ dec = single_token_labels("x\n{}) y") # System 1 option-line labels
123
+ lo, hi = head["slots"]["ranges"]["choice"]
124
+ assert [t for _, t in dec[: hi - lo]] == head["verbalizer_ids"][lo:hi], "first labels must be the trained A-P head"
125
+ base = tok.encode("Answer: (", add_special_tokens=False) # System 2 answer labels
126
+ ans = []
127
+ for lab in list(string.ascii_uppercase) + [a + b for a in string.ascii_uppercase for b in string.ascii_uppercase]:
128
+ ids = tok.encode(f"Answer: ({lab})", add_special_tokens=False)
129
+ if ids[: len(base)] == base and len(ids) == len(base) + 2:
130
+ ans.append((lab, ids[len(base)]))
131
+ if len(ans) == MAX_OPTIONS:
132
+ break
133
+ chat = tok.apply_chat_template([{"role": "user", "content": PLACEHOLDER}], tokenize=False, add_generation_prompt=True,
134
+ enable_thinking=True)
135
+ pre, post = chat.split(PLACEHOLDER)
136
+ raw = ("{%- for m in messages -%}{%- if m['content'] is string -%}{{ m['content'] }}{%- else -%}"
137
+ "{%- for c in m['content'] -%}{%- if c['type'] == 'text' -%}{{ c['text'] }}{%- else -%}" + prof["image"] +
138
+ "{%- endif -%}{%- endfor -%}{%- endif -%}{%- endfor -%}")
139
+ names = args.served_model_name
140
+ S.update(tok=tok, has_effort="reasoning_effort" in (tok.chat_template or ""), think_cache={},
141
+ max_logprobs=int(getattr(args, "max_logprobs", 20) or 20),
142
+ head=head, temps=temps, labels=[l for l, _ in dec], label_ids=[t for _, t in dec], ans_labels=ans, prof=prof,
143
+ think_pre=pre, think_post=post, raw=raw, end_think_id=tok.convert_tokens_to_ids(prof["end_think"]),
144
+ model=(names[0] if isinstance(names, list) else names) or args.model, model_type=mtype)
145
+
146
+
147
+ # ------------------------------------------------------------------ helpers
148
+ def _parts(state):
149
+ if isinstance(state, str):
150
+ return [{"type": "text", "text": state}], False
151
+ if isinstance(state, dict):
152
+ return [{"type": "text", "text": json.dumps(state, ensure_ascii=False)}], False
153
+ out, img = [], False
154
+ for p in state:
155
+ if isinstance(p, str):
156
+ out.append({"type": "text", "text": p})
157
+ elif isinstance(p, dict) and "image" in p:
158
+ out.append({"type": "image_url", "image_url": {"url": p["image"]}}); img = True
159
+ elif isinstance(p, dict) and p.get("type") == "image_url":
160
+ out.append(p); img = True
161
+ elif isinstance(p, dict) and p.get("type") == "text":
162
+ out.append(p)
163
+ else:
164
+ out.append({"type": "text", "text": json.dumps(p, ensure_ascii=False)})
165
+ return out, img
166
+
167
+
168
+ def _softmax(z):
169
+ m = max(z); e = [math.exp(x - m) for x in z]; s = sum(e)
170
+ return [x / s for x in e]
171
+
172
+
173
+ def _err(msg, code=400):
174
+ return JSONResponse({"error": {"message": msg, "type": "BadRequestError", "code": code}}, status_code=code)
175
+
176
+
177
+ class Upstream(Exception):
178
+ def __init__(self, resp):
179
+ self.resp = resp
180
+
181
+
182
+ def _check(out):
183
+ if hasattr(out, "error"):
184
+ raise Upstream(out)
185
+ return out
186
+
187
+
188
+ class Ctx:
189
+ def __init__(self, raw):
190
+ self.raw, self.requests, self.prompt_tokens, self.completion_tokens = raw, 0, 0, 0
191
+
192
+ def count(self, out):
193
+ self.requests += 1
194
+ if getattr(out, "usage", None):
195
+ self.prompt_tokens += out.usage.prompt_tokens or 0
196
+ self.completion_tokens += out.usage.completion_tokens or 0
197
+
198
+
199
+ def _readout_allowed(ids):
200
+ """Read-out path: restrict the next token to `ids` and return all of them as top logprobs when the server allows that
201
+ many (--max-logprobs); otherwise ask for `ids` explicitly with logprob_token_ids (chunks of 128). The first path also
202
+ works with speculative decoding; logprob_token_ids does not in this vLLM build. Both give the same distribution."""
203
+ return ids if len(ids) <= S["max_logprobs"] else None
204
+
205
+
206
+ async def _logprobs(ctx, content, has_img, ids, model, allowed=None):
207
+ """One-token read-out with a fallback to the other read-out path if the first one fails."""
208
+ try:
209
+ return await _logprobs_once(ctx, content, has_img, ids, model, allowed)
210
+ except Upstream:
211
+ raise
212
+ except Exception:
213
+ other = None if allowed is not None else (ids if len(ids) <= S["max_logprobs"] else None)
214
+ if other is None and allowed is None:
215
+ raise
216
+ return await _logprobs_once(ctx, content, has_img, ids, model, other)
217
+
218
+
219
+ async def _logprobs_once(ctx, content, has_img, ids, model, allowed=None):
220
+ """One-token read-out: {token_id: logprob} for `ids` after the content (text or chat parts)."""
221
+ lp = {}
222
+ step = CHUNK if allowed is None else len(ids)
223
+ for i in range(0, len(ids), step):
224
+ chunk = ids[i: i + step]
225
+ kw = dict(logprob_token_ids=chunk) if allowed is None else dict(allowed_token_ids=allowed)
226
+ if has_img:
227
+ r = ChatCompletionRequest(model=model, messages=[{"role": "user", "content": content}], chat_template=S["raw"],
228
+ add_generation_prompt=False, logprobs=True, top_logprobs=len(chunk) if allowed else 1, **kw, **READ)
229
+ out = _check(await ctx.raw.app.state.openai_serving_chat.create_chat_completion(r, ctx.raw)); ctx.count(out)
230
+ lp.update({int(t.token.split(":")[1]): t.logprob for t in out.choices[0].logprobs.content[0].top_logprobs})
231
+ else:
232
+ text = "".join(c["text"] for c in content)
233
+ r = CompletionRequest(model=model, prompt=text, logprobs=len(chunk) if allowed else 1, **kw, **READ)
234
+ out = _check(await ctx.raw.app.state.openai_serving_completion.create_completion(r, ctx.raw)); ctx.count(out)
235
+ lp.update({int(k.split(":")[1]): v for k, v in out.choices[0].logprobs.top_logprobs[0].items()})
236
+ if allowed is not None:
237
+ break
238
+ return lp
239
+
240
+
241
+ # ------------------------------------------------------------------ System 1
242
+ async def s1_pass(ctx, kind, parts, has_img, question, opts):
243
+ """One System 1 pass over `opts` (<=256). Returns probabilities aligned with opts."""
244
+ head, temps, prof = S["head"], S["temps"], S["prof"]
245
+ lo, hi = head["slots"]["ranges"][kind]
246
+ if kind == "choice":
247
+ n = len(opts); ids = S["label_ids"][:n]
248
+ bias = [head["bias"][lo + i] if lo + i < hi else 0.0 for i in range(n)]
249
+ lines = [f"{S['labels'][i]}) {o}" for i, o in enumerate(opts)]
250
+ else:
251
+ ids = head["verbalizer_ids"][lo:hi]; bias = head["bias"][lo:hi]; lines = opts
252
+ content = ([{"type": "text", "text": f"{prof['prefix']}[kind] {kind}\n[state] "}] + parts +
253
+ [{"type": "text", "text": f"\n[question] {question}\n[options]\n" + "\n".join(lines) + "\n[decision]:"}])
254
+ lp = await _logprobs(ctx, content, has_img, ids, LORA, allowed=_readout_allowed(ids))
255
+ return _softmax([(max(lp.get(t, -1e9), -1e9) + b) / temps[kind] for t, b in zip(ids, bias)])
256
+
257
+
258
+ def _groups(n, k=16):
259
+ g = math.ceil(n / k); base, extra = divmod(n, g); out, i = [], 0
260
+ for j in range(g):
261
+ size = base + (1 if j < extra else 0); out.append(list(range(i, i + size))); i += size
262
+ return out
263
+
264
+
265
+ async def s1_dist(ctx, kind, parts, has_img, question, opts, strategy):
266
+ if kind != "choice" or len(opts) <= 16 or strategy == "single":
267
+ return await s1_pass(ctx, kind, parts, has_img, question, opts)
268
+ n = len(opts)
269
+ if strategy == "permute":
270
+ import random
271
+ rng = random.Random(zlib.crc32(question.encode()))
272
+ orders = [list(range(n))] + [rng.sample(range(n), n) for _ in range(3)]
273
+ res = await asyncio.gather(*(s1_pass(ctx, kind, parts, has_img, question, [opts[i] for i in o]) for o in orders))
274
+ p = [0.0] * n
275
+ for o, r in zip(orders, res):
276
+ for i, v in zip(o, r):
277
+ p[i] += v / len(orders)
278
+ return p
279
+ groups = _groups(n) # tournament: groups of <=16 in the given order (in parallel), then a final of 16
280
+ parts_g = await asyncio.gather(*(s1_pass(ctx, kind, parts, has_img, question, [opts[i] for i in g]) for g in groups))
281
+ in_group = {o: p for g, ps in zip(groups, parts_g) for o, p in zip(g, ps)}
282
+ chosen = [max(g, key=lambda o: (in_group[o], -o)) for g in groups]
283
+ rest = sorted((o for g in groups for o in g if o not in set(chosen)), key=lambda o: (-in_group[o], o))
284
+ fin = sorted(chosen + rest[: max(0, 16 - len(chosen))])
285
+ final = dict(zip(fin, await s1_pass(ctx, kind, parts, has_img, question, [opts[i] for i in fin])))
286
+ group_of = {o: gi for gi, g in enumerate(groups) for o in g}
287
+ share = [0.0] * len(groups); cap = [0.0] * len(groups)
288
+ for f in fin:
289
+ share[group_of[f]] += final[f]; cap[group_of[f]] += in_group[f]
290
+ among = sum(a * b for a, b in zip(share, cap))
291
+ p = [final[o] * among if o in final else share[group_of[o]] * in_group[o] for o in range(n)]
292
+ s = sum(p)
293
+ return [x / s for x in p]
294
+
295
+
296
+ # ------------------------------------------------------------------ System 2 (thinking)
297
+ def _think_frame(kwargs):
298
+ """Chat-template prefix / suffix around the user turn, thinking on, with the caller's template kwargs (cached)."""
299
+ key = json.dumps(kwargs or {}, sort_keys=True)
300
+ if key not in S["think_cache"]:
301
+ kw = {k: v for k, v in (kwargs or {}).items() if k != "enable_thinking"}
302
+ chat = S["tok"].apply_chat_template([{"role": "user", "content": PLACEHOLDER}], tokenize=False, add_generation_prompt=True,
303
+ enable_thinking=True, **kw)
304
+ S["think_cache"][key] = tuple(chat.split(PLACEHOLDER))
305
+ return S["think_cache"][key]
306
+
307
+
308
+ async def s2_dist(ctx, kind, parts, has_img, question, opts, budget, want_text, tmpl_kwargs=None):
309
+ """The base model thinks over the same input; the answer-letter distribution is read after the thinking channel."""
310
+ shown = ["Yes (true)", "No (false)"] if kind == "noul" else opts
311
+ labs = S["ans_labels"][: len(shown)]
312
+ body = "\n".join(f"({l}) {o}" for (l, _), o in zip(labs, shown))
313
+ tail = (f"\n\nQuestion: {question}\n\nOptions:\n{body}\n\n"
314
+ "Think it through carefully, then give your final answer on the last line in the form: Answer: (X)")
315
+ pre, post = _think_frame(tmpl_kwargs)
316
+ user = [{"type": "text", "text": pre}] + parts + [{"type": "text", "text": tail + post}]
317
+ seed = zlib.crc32((question + body).encode()) & 0x7FFFFFFF
318
+ t0 = time.time()
319
+ gen = ChatCompletionRequest(model=S["model"], messages=[{"role": "user", "content": user}], chat_template=S["raw"],
320
+ add_generation_prompt=False, add_special_tokens=False, max_tokens=budget, seed=seed, # None: up to the context window
321
+ stop_token_ids=[S["end_think_id"]], skip_special_tokens=False)
322
+ out = _check(await ctx.raw.app.state.openai_serving_chat.create_chat_completion(gen, ctx.raw)); ctx.count(out)
323
+ thought = out.choices[0].message.content or ""
324
+ finished = out.choices[0].finish_reason == "stop"
325
+ ntok = out.usage.completion_tokens if out.usage else None
326
+ read = user + [{"type": "text", "text": thought + S["prof"]["end_think"] + S["prof"]["after_think"] + "Answer: ("}]
327
+ ids = [t for _, t in labs]
328
+ lp = await _logprobs(ctx, read, True, ids, S["model"], allowed=_readout_allowed(ids))
329
+ p = _softmax([max(lp.get(t, -1e9), -1e9) for t in ids])
330
+ if kind == "noul":
331
+ p = [p[1], p[0]] # (A) yes / (B) no -> [P(false), P(true)]
332
+ info = {"think_tokens": ntok, "think_seconds": round(time.time() - t0, 3), "finished_within_budget": finished}
333
+ if want_text:
334
+ info["reasoning"] = thought.replace("<|channel>thought\n", "").strip()
335
+ return p, info
336
+
337
+
338
+ def _fold(p1, p2, w):
339
+ return [(1 - w) * x + w * y for x, y in zip(p1, p2)]
340
+
341
+
342
+ # ------------------------------------------------------------------ routes
343
+ router = APIRouter()
344
+
345
+
346
+ @router.get("/v1/decide/info")
347
+ async def info():
348
+ p = S["prof"]
349
+ return {"protocol": PROTOCOL, "model": S["model"], "model_type": S["model_type"], "max_options": len(S["labels"]),
350
+ "native_choice_options": len(S["head"]["slots"]["verbalizers"]) - 8, "temperatures": S["temps"],
351
+ "defaults": {"strategy": p["strategy"], "thinking": p["thinking"], "threshold": p["threshold"], "mix": p["mix"],
352
+ "think_budget": None},
353
+ "reasoning_controls": {"enable_thinking": True, "reasoning_effort": ["xhigh", "medium", "low"] if S["has_effort"] else None,
354
+ "think_budget": "max thinking tokens (default: up to the context window)"}}
355
+
356
+
357
+ @router.post("/v1/decide")
358
+ async def decide(req: DecideRequest, raw: Request):
359
+ t0 = time.time()
360
+ if req.kind == "choice":
361
+ opts = req.options or []
362
+ if not 2 <= len(opts) <= len(S["labels"]):
363
+ return _err(f"choice needs 2-{len(S['labels'])} options, got {len(opts)}")
364
+ else:
365
+ opts = ["false", "true"] if req.kind == "noul" else [str(i) for i in range(6)]
366
+ prof = S["prof"]
367
+ thinking = prof["thinking"] if req.thinking == "default" else req.thinking
368
+ if req.kind == "score":
369
+ if req.thinking in ("auto", "on"):
370
+ return _err("thinking is supported for noul and choice")
371
+ thinking = "off"
372
+ tmpl = dict(req.chat_template_kwargs or {})
373
+ if req.reasoning_effort is not None:
374
+ if not S["has_effort"]:
375
+ return _err("this base model has no reasoning_effort setting; control the reasoning length with think_budget")
376
+ tmpl["reasoning_effort"] = req.reasoning_effort
377
+ strategy = prof["strategy"] if req.strategy == "auto" else req.strategy
378
+ tau = prof["threshold"] if req.threshold is None else req.threshold
379
+ parts, has_img = _parts(req.state)
380
+ ctx = Ctx(raw)
381
+ try:
382
+ if req.system2_only:
383
+ if req.kind == "score":
384
+ return _err("system2_only is supported for noul and choice")
385
+ p2, think = await s2_dist(ctx, req.kind, parts, has_img, req.question, opts, req.think_budget, req.return_reasoning, tmpl)
386
+ k = max(range(len(p2)), key=p2.__getitem__)
387
+ return {"kind": req.kind, "options": opts, "probabilities": p2, "choice_index": k, "choice": opts[k], "system": 2,
388
+ "model": S["model"], "thinking": {"used": True, "budget": req.think_budget, **think},
389
+ "usage": {"prompt_tokens": ctx.prompt_tokens, "completion_tokens": ctx.completion_tokens},
390
+ "elapsed_seconds": time.time() - t0, "num_model_requests": ctx.requests}
391
+ p1 = await s1_dist(ctx, req.kind, parts, has_img, req.question, opts, strategy)
392
+ probs, think = p1, None
393
+ if thinking == "on" or (thinking == "auto" and max(p1) < tau):
394
+ p2, think = await s2_dist(ctx, req.kind, parts, has_img, req.question, opts, req.think_budget, req.return_reasoning, tmpl)
395
+ probs = _fold(p1, p2, prof["mix"])
396
+ think = {"used": True, **think}
397
+ if req.debug:
398
+ think.update(system1=p1, system2=p2)
399
+ elif thinking != "off":
400
+ think = {"used": False}
401
+ if req.debug:
402
+ think["system1"] = p1
403
+ except Upstream as e:
404
+ return JSONResponse(e.resp.model_dump(), status_code=e.resp.error.code)
405
+ k = max(range(len(probs)), key=probs.__getitem__)
406
+ native = req.kind != "choice" or len(opts) <= 16
407
+ resp = {"kind": req.kind, "effective_kind": req.kind, "options": opts, "probabilities": probs, "choice_index": k,
408
+ "choice": opts[k], "adaptation": "native" if native else f"{strategy}", "protocol": PROTOCOL, "model": S["model"],
409
+ "usage": {"prompt_tokens": ctx.prompt_tokens, "completion_tokens": ctx.completion_tokens,
410
+ "total_tokens": ctx.prompt_tokens + ctx.completion_tokens},
411
+ "elapsed_seconds": time.time() - t0, "num_model_requests": ctx.requests}
412
+ if think is not None:
413
+ resp["thinking"] = {"mode": thinking, "threshold": tau, "budget": req.think_budget, **({"chat_template_kwargs": tmpl} if tmpl else {}), **think}
414
+ return resp
415
+
416
+
417
+ _build_app = entry.build_app
418
+
419
+
420
+ def build_app(args, *a, **kw):
421
+ app = _build_app(args, *a, **kw)
422
+ setup(args)
423
+ app.include_router(router)
424
+ return app
425
+
426
+
427
+ entry.build_app = build_app
428
+
429
+ if __name__ == "__main__":
430
+ entry.main()