OneStarDao commited on
Commit
26f293f
Β·
verified Β·
1 Parent(s): 54b95bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -35
app.py CHANGED
@@ -3,19 +3,26 @@ matplotlib.use("Agg")
3
 
4
  from PIL import Image
5
  import pandas as pd, plotly.express as px, gradio as gr
 
6
  from transformers import AutoTokenizer, AutoModelForCausalLM
7
  from wfgy_sdk import get_engine
8
  from wfgy_sdk.evaluator import compare_logits, plot_histogram
9
 
10
- # tiny model for demo
 
 
11
  tok = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")
12
  mdl = AutoModelForCausalLM.from_pretrained("sshleifer/tiny-gpt2")
13
  eng = get_engine()
14
 
15
- # runtime history (start with a dummy zero so the plot is never empty)
 
 
16
  history = {"step": [0], "var": [0.0], "kl": [0.0]}
17
 
18
- # paper benchmark absolute numbers
 
 
19
  paper_df = pd.DataFrame({
20
  "Benchmark": ["MMLU","GSM8K","BBH","MathBench","TruthfulQA",
21
  "XNLI","MLQA","LongBench","VQAv2","OK-VQA"],
@@ -23,14 +30,55 @@ paper_df = pd.DataFrame({
23
  "WFGY": [89.8,98.7,100.7,87.4,90.4,77.3,106.6,69.6,86.6,86.8]
24
  })
25
  paper_df["Abs_gain"] = (paper_df["WFGY"] - paper_df["Baseline"]).round(1)
26
- paper_df["Rel_gain%"] = ((paper_df["Abs_gain"] / paper_df["Baseline"])*100).round(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  def run(prompt: str):
29
- prompt = prompt.strip()
30
- if not prompt:
31
- return "", "", "", None, plot_history()
32
- ids = tok(prompt, return_tensors="pt").input_ids
33
- rawL = mdl(ids).logits[0,-1].detach().cpu().numpy()
 
34
  G = np.random.randn(256).astype(np.float32)
35
  I = G + np.random.normal(scale=0.05, size=256).astype(np.float32)
36
  modL = eng.run(I, G, rawL)
@@ -38,52 +86,46 @@ def run(prompt: str):
38
  m = compare_logits(rawL, modL)
39
  step = len(history["step"])
40
  history["step"].append(step)
41
- history["var"].append(m["var_drop"]*100)
42
  history["kl"].append(m["kl"])
43
 
44
  fig = plot_histogram(rawL, modL)
45
  buf = io.BytesIO(); fig.savefig(buf, format="png"); buf.seek(0)
46
  img = Image.open(buf)
47
 
48
- headline = f"β–Ό var {m['var_drop']*100:4.1f}% | KL {m['kl']:.3f}"
49
- note = f"*top-1 token {'changed' if not m['top1'] else 'kept'}*"
50
 
51
- raw_text = prompt + tok.decode(int(rawL.argmax()))
52
- mod_text = prompt + tok.decode(int(modL.argmax()))
53
 
54
- return raw_text, mod_text, headline + " " + note, img, plot_history()
55
 
56
- def plot_history():
57
- df = pd.DataFrame(history)
58
- return px.line(df, x="step", y=["var","kl"],
59
- labels={"value":"metric","step":"call"},
60
- title="history (var% ↓ & KL)").update_layout(height=260)
61
-
62
- def clear_hist():
63
- history["step"][:] = [0]
64
- history["var"][:] = [0.0]
65
- history["kl"][:] = [0.0]
66
- return plot_history()
67
-
68
- with gr.Blocks(title="WFGY variance gate") as demo:
69
  gr.Markdown("# 🧠 WFGY simulation demo")
70
  prompt = gr.Textbox(label="Prompt", value="Explain SchrΓΆdinger's cat")
71
  run_btn = gr.Button("πŸš€ Run")
 
72
  with gr.Row():
73
- raw_box = gr.Textbox(label="Raw GPT-2")
74
- mod_box = gr.Textbox(label="After WFGY")
 
75
  headline = gr.Markdown()
76
  hist_img = gr.Image(type="pil", label="Logit histogram")
77
- hist_plot = gr.Plot(label="History")
78
  clr_btn = gr.Button("Clear history")
79
 
80
  with gr.Accordion("Paper benchmarks", open=False):
81
- gr.DataFrame(paper_df, interactive=False, wrap=True)
 
82
 
83
- gr.Markdown("---\n⭐ **10 000 GitHub stars before 2025-08-01 unlock WFGY 2.0**")
84
 
85
- run_btn.click(run, prompt, [raw_box, mod_box, headline, hist_img, hist_plot])
86
- clr_btn.click(clear_hist, None, hist_plot)
 
87
 
88
  if __name__ == "__main__":
89
  demo.queue().launch()
 
3
 
4
  from PIL import Image
5
  import pandas as pd, plotly.express as px, gradio as gr
6
+ import torch
7
  from transformers import AutoTokenizer, AutoModelForCausalLM
8
  from wfgy_sdk import get_engine
9
  from wfgy_sdk.evaluator import compare_logits, plot_histogram
10
 
11
+ # ────────────────────────────
12
+ # tiny model + engine
13
+ # ────────────────────────────
14
  tok = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")
15
  mdl = AutoModelForCausalLM.from_pretrained("sshleifer/tiny-gpt2")
16
  eng = get_engine()
17
 
18
+ # ────────────────────────────
19
+ # runtime history (dummy zero so line is never empty)
20
+ # ────────────────────────────
21
  history = {"step": [0], "var": [0.0], "kl": [0.0]}
22
 
23
+ # ────────────────────────────
24
+ # paper benchmark table
25
+ # ────────────────────────────
26
  paper_df = pd.DataFrame({
27
  "Benchmark": ["MMLU","GSM8K","BBH","MathBench","TruthfulQA",
28
  "XNLI","MLQA","LongBench","VQAv2","OK-VQA"],
 
30
  "WFGY": [89.8,98.7,100.7,87.4,90.4,77.3,106.6,69.6,86.6,86.8]
31
  })
32
  paper_df["Abs_gain"] = (paper_df["WFGY"] - paper_df["Baseline"]).round(1)
33
+ paper_df["Rel_gain%"] = ((paper_df["Abs_gain"] / paper_df["Baseline"]) * 100).round(0)
34
+
35
+ styled_df = (
36
+ paper_df.style
37
+ .background_gradient(subset=["Abs_gain"], cmap="Greens")
38
+ .background_gradient(subset=["Rel_gain%"], cmap="Greens")
39
+ .format({"Abs_gain": "{:.1f}", "Rel_gain%": "{:.0f}"})
40
+ )
41
+
42
+ paper_bar = px.bar(
43
+ paper_df, x="Benchmark", y="Rel_gain%",
44
+ title="Relative gain (%)", color="Rel_gain%",
45
+ color_continuous_scale="Greens", height=300
46
+ )
47
+
48
+ # ────────────────────────────
49
+ # helpers
50
+ # ────────────────────────────
51
+ def top5_tokens(logits: np.ndarray):
52
+ """return list of (token, prob) sorted desc"""
53
+ probs = torch.softmax(torch.tensor(logits), dim=0).numpy()
54
+ idx = probs.argsort()[-5:][::-1]
55
+ items = []
56
+ for i in idx:
57
+ token = tok.decode(int(i)).replace("\n", "\\n")
58
+ prob = probs[i]
59
+ items.append(f"{token!r}: {prob:.3f}")
60
+ return "\n".join(items)
61
 
62
+ def plot_history():
63
+ df = pd.DataFrame(history)
64
+ return px.line(df, x="step", y=["var", "kl"],
65
+ labels={"value":"metric","step":"call"},
66
+ title="history (var% ↓ & KL)").update_layout(height=260)
67
+
68
+ def clear_history():
69
+ history["step"][:] = [0]; history["var"][:]=[0.0]; history["kl"][:]=[0.0]
70
+ return plot_history()
71
+
72
+ # ────────────────────────────
73
+ # main run
74
+ # ────────────────────────────
75
  def run(prompt: str):
76
+ p = prompt.strip()
77
+ if not p:
78
+ return "", "", "", "", None, plot_history()
79
+
80
+ ids = tok(p, return_tensors="pt").input_ids
81
+ rawL = mdl(ids).logits[0, -1].detach().cpu().numpy()
82
  G = np.random.randn(256).astype(np.float32)
83
  I = G + np.random.normal(scale=0.05, size=256).astype(np.float32)
84
  modL = eng.run(I, G, rawL)
 
86
  m = compare_logits(rawL, modL)
87
  step = len(history["step"])
88
  history["step"].append(step)
89
+ history["var"].append(m["var_drop"] * 100)
90
  history["kl"].append(m["kl"])
91
 
92
  fig = plot_histogram(rawL, modL)
93
  buf = io.BytesIO(); fig.savefig(buf, format="png"); buf.seek(0)
94
  img = Image.open(buf)
95
 
96
+ headline = f"β–Ό var {m['var_drop']*100:4.1f}% | KL {m['kl']:.3f} | top-1 {'kept' if m['top1'] else 'changed'}"
 
97
 
98
+ raw_top5 = top5_tokens(rawL)
99
+ mod_top5 = top5_tokens(modL)
100
 
101
+ return raw_top5, mod_top5, headline, img, plot_history()
102
 
103
+ # ────────────────────────────
104
+ # UI layout
105
+ # ────────────────────────────
106
+ with gr.Blocks(title="WFGY variance gate demo") as demo:
 
 
 
 
 
 
 
 
 
107
  gr.Markdown("# 🧠 WFGY simulation demo")
108
  prompt = gr.Textbox(label="Prompt", value="Explain SchrΓΆdinger's cat")
109
  run_btn = gr.Button("πŸš€ Run")
110
+
111
  with gr.Row():
112
+ raw_box = gr.Textbox(label="Raw top-5 tokens", lines=6)
113
+ mod_box = gr.Textbox(label="WFGY top-5 tokens", lines=6)
114
+
115
  headline = gr.Markdown()
116
  hist_img = gr.Image(type="pil", label="Logit histogram")
117
+ hist_plot = gr.Plot()
118
  clr_btn = gr.Button("Clear history")
119
 
120
  with gr.Accordion("Paper benchmarks", open=False):
121
+ gr.DataFrame(value=styled_df, interactive=False, wrap=True)
122
+ gr.Plot(paper_bar)
123
 
124
+ gr.Markdown("---\n⭐ **10 000 GitHub stars before 2025-08-01 unlock WFGY 2.0**")
125
 
126
+ run_btn.click(run, prompt,
127
+ [raw_box, mod_box, headline, hist_img, hist_plot])
128
+ clr_btn.click(clear_history, None, hist_plot)
129
 
130
  if __name__ == "__main__":
131
  demo.queue().launch()