SeaWolf-AI commited on
Commit
6f06b4d
·
verified ·
1 Parent(s): bad22db

ZTC usage example

Browse files
Files changed (1) hide show
  1. ztc/usage.py +55 -0
ztc/usage.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Zero-Token Confidence (ZTC) — usage
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_darwin397b.npz (45 KB)
8
+ # input : final-layer hidden state of the last prompt token (4096-dim)
9
+ # output : score, and a calibrated probability in [0, 1]
10
+ #
11
+ # Reported performance on this model (PubMedQA, 539 items, 146 incorrect):
12
+ # self-reported confidence AUROC 0.7646
13
+ # ZTC AUROC 0.8801 (permutation null z = 13.31)
14
+
15
+ import numpy as np
16
+ import torch
17
+ from transformers import AutoModel, AutoTokenizer
18
+
19
+ MODEL = "FINAL-Bench/Darwin-397B-ZTC"
20
+ PROBE = "ztc/ztc_probe_darwin397b.npz"
21
+
22
+
23
+ class ZTC:
24
+ def __init__(self, path=PROBE):
25
+ z = np.load(path)
26
+ self.w = z["w"].astype(np.float32)
27
+ self.mu = z["mu"].astype(np.float32)
28
+ self.sd = z["sd"].astype(np.float32)
29
+ self.s_mean = float(z["s_mean"]); self.s_std = float(z["s_std"])
30
+ self.A = float(z["cal_A"]); self.B = float(z["cal_B"])
31
+
32
+ def score(self, hidden):
33
+ """hidden: (4096,) or (batch, 4096) final-layer state of the last prompt token."""
34
+ h = np.asarray(hidden, dtype=np.float32)
35
+ s = ((h - self.mu) / self.sd) @ self.w
36
+ p = 1.0 / (1.0 + np.exp(-(self.A * (s - self.s_mean) / self.s_std + self.B)))
37
+ return s, p
38
+
39
+
40
+ # --- one forward pass, zero generated tokens -------------------------------
41
+ tok = AutoTokenizer.from_pretrained(MODEL)
42
+ model = AutoModel.from_pretrained(MODEL, dtype=torch.bfloat16, device_map="auto").eval()
43
+ ztc = ZTC()
44
+
45
+ prompt = "Question: ...\nAnswer:"
46
+ b = tok(prompt, return_tensors="pt").to(next(model.parameters()).device)
47
+ with torch.no_grad():
48
+ h = model(**b).last_hidden_state[0, -1].float().cpu().numpy()
49
+
50
+ s, p = ztc.score(h)
51
+ print("ZTC score %.3f -> P(correct) = %.3f" % (s, p))
52
+
53
+ # Gate the action, not the answer:
54
+ # if p < THRESHOLD: do not call the tool / escalate / answer "I don't know"
55
+ # else: generate as usual