SeaWolf-AI commited on
Commit
7b875ae
·
verified ·
1 Parent(s): 3b51b43

ztc: ship early ZTC probe (AUROC 0.64) + handler

Browse files
Files changed (5) hide show
  1. README.md +2 -0
  2. handler.py +58 -0
  3. ztc/README.md +33 -0
  4. ztc/usage.py +47 -0
  5. ztc/ztc_probe_darwin180rsi.npz +3 -0
README.md CHANGED
@@ -253,6 +253,8 @@ print(h({"inputs": "What is 17 * 23?"}))
253
 
254
  Same format as [Darwin-397B-ZTC](https://huggingface.co/FINAL-Bench/Darwin-397B-ZTC). The readout is fitted only on practice data that is disjoint from every benchmark reported here.
255
 
 
 
256
  ---
257
 
258
  ## 🏆 Results
 
253
 
254
  Same format as [Darwin-397B-ZTC](https://huggingface.co/FINAL-Bench/Darwin-397B-ZTC). The readout is fitted only on practice data that is disjoint from every benchmark reported here.
255
 
256
+ **Status: early release.** This probe reaches an AUROC of 0.64 on our held-out validation split: a coarse signal for routing and review, not a correctness guarantee. A retrained probe with more data will replace it. Details in [`ztc/README.md`](https://huggingface.co/FINAL-Bench/Darwin-180B-RSI/blob/main/ztc/README.md).
257
+
258
  ---
259
 
260
  ## 🏆 Results
handler.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Darwin-180B-RSI handler — answer + Zero-Token Confidence (ZTC) in one JSON.
3
+
4
+ ZTC reads the final-layer hidden state of the last prompt token ONCE, before generation,
5
+ and returns the probability that the answer the model is about to produce is correct.
6
+ No extra tokens are generated and no second model is needed.
7
+
8
+ Output (one item per input):
9
+ {"answer": str, "confidence": float, "ztc_score": float, "truncated": bool}
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ from typing import Any, Dict, List
15
+
16
+ import numpy as np
17
+ import torch
18
+ from transformers import AutoModelForImageTextToText, AutoProcessor
19
+
20
+
21
+ class ZTC:
22
+ def __init__(self, path: str):
23
+ z = np.load(path)
24
+ self.w, self.mu, self.sd = z["w"].astype(np.float32), z["mu"].astype(np.float32), z["sd"].astype(np.float32)
25
+ self.s_mean, self.s_std = float(z["s_mean"]), float(z["s_std"])
26
+ self.A, self.B = float(z["cal_A"]), float(z["cal_B"])
27
+
28
+ def score(self, h: np.ndarray):
29
+ s = ((np.asarray(h, np.float32) - self.mu) / self.sd) @ self.w
30
+ p = 1.0 / (1.0 + np.exp(-(self.A * (s - self.s_mean) / self.s_std + self.B)))
31
+ return float(s), float(p)
32
+
33
+
34
+ class EndpointHandler:
35
+ def __init__(self, path: str = ""):
36
+ self.proc = AutoProcessor.from_pretrained(path)
37
+ self.model = AutoModelForImageTextToText.from_pretrained(path, torch_dtype="auto", device_map="auto").eval()
38
+ self.ztc = ZTC(os.path.join(path, "ztc", "ztc_probe_darwin180rsi.npz"))
39
+
40
+ @torch.no_grad()
41
+ def _one(self, prompt: str, max_new_tokens: int) -> Dict[str, Any]:
42
+ msgs = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
43
+ text = self.proc.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
44
+ enc = self.proc(text=[text], return_tensors="pt").to(self.model.device)
45
+ # 1) ZTC: one forward pass over the prompt, final layer, last token — zero generated tokens
46
+ h = self.model(**enc, output_hidden_states=True, use_cache=False).hidden_states[-1][0, -1].float().cpu().numpy()
47
+ s, p = self.ztc.score(h)
48
+ # 2) answer
49
+ out = self.model.generate(**enc, max_new_tokens=max_new_tokens, do_sample=True, temperature=1.0, top_p=0.95, top_k=20)
50
+ gen = out[0, enc["input_ids"].shape[1]:]
51
+ answer = self.proc.decode(gen, skip_special_tokens=True)
52
+ return {"answer": answer, "confidence": round(p, 4), "ztc_score": round(s, 4), "truncated": bool(len(gen) >= max_new_tokens)}
53
+
54
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
55
+ inputs = data.get("inputs")
56
+ inputs = [inputs] if isinstance(inputs, str) else inputs
57
+ mnt = int((data.get("parameters") or {}).get("max_new_tokens", 32768))
58
+ return [self._one(x, mnt) for x in inputs]
ztc/README.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ZTC probe for Darwin-180B-RSI (early release)
2
+
3
+ Zero-Token Confidence (ZTC) estimates, before any answer token is generated, how likely the model is to answer a question correctly. It reads the model's hidden state at the last prompt token and maps it to a probability with a small linear probe.
4
+
5
+ ## Files
6
+
7
+ | File | What it is |
8
+ |:--|:--|
9
+ | `ztc_probe_darwin180rsi.npz` | Probe weights: ridge regression on the final-layer hidden state of the last prompt token, followed by Platt scaling |
10
+ | `handler.py` | Loads the probe and returns a confidence score for a prompt |
11
+ | `usage.py` | Minimal usage example |
12
+
13
+ ## How it works
14
+
15
+ 1. Run the prompt through Darwin-180B-RSI once, with no generation.
16
+ 2. Take the final-layer hidden state at the last prompt token.
17
+ 3. Apply the ridge weights and bias, then the Platt calibration, to get a probability in [0, 1].
18
+
19
+ Cost is one forward pass over the prompt. No answer tokens are produced.
20
+
21
+ ## Status and measured quality
22
+
23
+ This is an early probe. On our held-out validation split it reaches an **AUROC of 0.64**. That is a weak signal, useful for coarse routing (for example, flagging questions for a second pass or for review), not for deciding on its own whether an answer is right.
24
+
25
+ A retrained version with more training data is planned and will replace this file. The numbers above will be updated when it ships.
26
+
27
+ ## Intended use
28
+
29
+ - Ranking or filtering questions by expected difficulty
30
+ - Deciding where to spend extra samples or a longer thinking budget
31
+ - A gate that sends low-confidence cases to a human or a stronger check
32
+
33
+ Not intended as a correctness guarantee.
ztc/usage.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Zero-Token Confidence (ZTC) — usage for Darwin-180B-RSI
2
+ #
3
+ # ZTC reads the model's own internal state ONCE, before generation, and returns
4
+ # the probability that the answer the model is about to produce will be correct.
5
+ # No extra tokens are generated. No second model is required.
6
+ #
7
+ # probe file : ztc/ztc_probe_darwin180rsi.npz
8
+ # input : final-layer hidden state of the last prompt token (2560-dim)
9
+ # output : score, and a calibrated probability in [0, 1]
10
+
11
+ import json
12
+ import numpy as np
13
+ import torch
14
+ from transformers import AutoModelForImageTextToText, AutoProcessor
15
+
16
+ MODEL = "FINAL-Bench/Darwin-180B-RSI"
17
+ PROBE = "ztc/ztc_probe_darwin180rsi.npz"
18
+
19
+
20
+ class ZTC:
21
+ def __init__(self, path=PROBE):
22
+ z = np.load(path)
23
+ self.w, self.mu, self.sd = z["w"].astype(np.float32), z["mu"].astype(np.float32), z["sd"].astype(np.float32)
24
+ self.s_mean, self.s_std = float(z["s_mean"]), float(z["s_std"])
25
+ self.A, self.B = float(z["cal_A"]), float(z["cal_B"])
26
+
27
+ def score(self, hidden):
28
+ s = ((np.asarray(hidden, np.float32) - self.mu) / self.sd) @ self.w
29
+ p = 1.0 / (1.0 + np.exp(-(self.A * (s - self.s_mean) / self.s_std + self.B)))
30
+ return float(s), float(p)
31
+
32
+
33
+ proc = AutoProcessor.from_pretrained(MODEL)
34
+ model = AutoModelForImageTextToText.from_pretrained(MODEL, torch_dtype=torch.bfloat16, device_map="auto").eval()
35
+ ztc = ZTC()
36
+
37
+ question = "What is 17 * 23?"
38
+ text = proc.apply_chat_template([{"role": "user", "content": [{"type": "text", "text": question}]}], add_generation_prompt=True, tokenize=False)
39
+ enc = proc(text=[text], return_tensors="pt").to(model.device)
40
+ with torch.no_grad():
41
+ h = model(**enc, output_hidden_states=True, use_cache=False).hidden_states[-1][0, -1].float().cpu().numpy()
42
+ s, p = ztc.score(h)
43
+ print(json.dumps({"ztc_score": round(s, 4), "confidence": round(p, 4)}))
44
+
45
+ # Gate the action, not the answer:
46
+ # if p < THRESHOLD: do not call the tool / escalate / answer "I don't know"
47
+ # else: generate as usual
ztc/ztc_probe_darwin180rsi.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b520ad7c791b8dfd76ba6a029035d8969fe334cd837a1e4b05dd6589a587897
3
+ size 32450