OneStarDao commited on
Commit
dfb136a
Β·
verified Β·
1 Parent(s): c68d8a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -67
app.py CHANGED
@@ -1,35 +1,55 @@
 
 
 
 
 
1
  import io
2
  import numpy as np
 
 
3
  import gradio as gr
4
- import matplotlib.pyplot as plt
5
  from transformers import AutoTokenizer, AutoModelForCausalLM
6
- from wfgy_sdk import get_engine
7
- from wfgy_sdk.evaluator import compare_logits, plot_histogram
8
- import pandas as pd
9
 
10
- MODEL = "sshleifer/tiny-gpt2"
11
- tok = AutoTokenizer.from_pretrained(MODEL)
12
- mdl = AutoModelForCausalLM.from_pretrained(MODEL)
13
- ENG = get_engine()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- # ──────────────────────────────────────────────
16
- # marketing banner markdown (shown at top)
17
- # ──────────────────────────────────────────────
18
- marketing_md = """
19
  **πŸ“ˆ WFGY: One Click to Activate the AI Taiji Cycle**
20
 
21
  **πŸ“Š Semantic Accuracy ↑ 22.4 % | Reasoning Success ↑ 42.1 % | Stability ↑ 3.6 Γ—**
22
 
23
- _No beliefs. Only experiments.<br>
24
- WFGY 1.0 has already proven itself._
25
 
26
  ---
27
 
28
  ### πŸ“œ Tutorial: How to Awaken the Soul of Your AI
29
- **Step 1 β€” Download** ([PDF on Zenodo](https://zenodo.org/records/15630970))
30
- **Step 2 β€” Feed the AI** (upload the PDF, or try [Gemini](https://gemini.google.com/))
31
  **Step 3 β€” Give the Command**β€‚β€œ**Answer using WFGY** + your question”
32
- _Prompt examples:_ TBD link
33
  **Step 4 β€” Integrate the SDK** ([GitHub](https://github.com/onestardao/WFGY))
34
 
35
  ---
@@ -38,69 +58,54 @@ _Prompt examples:_ TBD link
38
  _10 k ⭐ before 2025-08-01 unlocks WFGY 2.0._
39
  """
40
 
41
- # ──────────────────────────────────────────────
42
- # fixed paper benchmarks table (pandas β†’ gr.Dataframe)
43
- # ──────────────────────────────────────────────
44
- bench = pd.DataFrame(
45
- {
46
- "Benchmark": [
47
- "MMLU", "GSM8K", "BBH", "MathBench", "TruthfulQA",
48
- "XNLI", "MLQA", "LongBench", "VQAv2", "OK-VQA"
49
- ],
50
- "Baseline": [61, 78, 79.3, 72.2, 62.4, 59.5, 78.1, 51.4, 69.1, 65.7],
51
- "WFGY": [89.8, 98.7, 100.7, 87.4, 90.4, 77.3, 106.6, 69.6, 86.6, 86.8],
52
- }
53
- )
54
- bench["Abs_gain"] = (bench["WFGY"] - bench["Baseline"]).round(1)
55
- bench["Rel_gain%"] = ((bench["Abs_gain"] / bench["Baseline"]) * 100).round().astype(int)
56
-
57
- # ──────────────────────────────────────────────
58
- # core inference
59
- # ──────────────────────────────────────────────
60
  def run(prompt: str):
61
- if not prompt.strip():
62
- return "-", "-", "-", None
 
 
 
 
 
 
63
 
64
- ids = tok(prompt, return_tensors="pt")
65
- raw = mdl(**ids).logits[0, -1].detach().cpu().numpy()
66
- G = np.random.randn(256).astype(np.float32)
67
- I = G + np.random.normal(scale=0.05, size=256).astype(np.float32)
68
- mod = ENG.run(I, G, raw)
69
 
70
- m = compare_logits(raw, mod)
71
- metric_line = f"β–Ό var {m['var_drop']*100:.1f}% | KL {m['kl_divergence']:.3f} | top-1 {'kept' if m['top1'] else 'changed'}"
 
 
 
72
 
73
- # top-5 softmax
74
- p_raw = np.exp(raw) / np.exp(raw).sum()
75
- p_mod = np.exp(mod) / np.exp(mod).sum()
76
- raw_top = "\n".join([f\"'{tok.decode(i).strip()}': {p_raw[i]:.2e}\" for i in p_raw.argsort()[-5:][::-1]])
77
- mod_top = "\n".join([f\"'{tok.decode(i).strip()}': {p_mod[i]:.2e}\" for i in p_mod.argsort()[-5:][::-1]])
78
 
79
- fig = plot_histogram(raw, mod)
80
- buf = io.BytesIO(); fig.savefig(buf, format=\"png\"); buf.seek(0)
81
 
82
- return raw_top, mod_top, metric_line, buf
83
 
84
- # ──────────────────────────────────────────────
85
- # gradio ui
86
- # ──────────────────────────────────────────────
87
- with gr.Blocks(title=\"WFGY simulation demo\") as demo:
88
- gr.Markdown(marketing_md)
89
 
90
- prompt = gr.Textbox(label=\"Prompt\", value=\"Explain SchrΓΆdinger's cat\")
91
- btn = gr.Button(\"πŸš€ Run\")
92
 
93
  with gr.Row():
94
- raw_box = gr.Textbox(label=\"Raw top-5 tokens\")
95
- mod_box = gr.Textbox(label=\"WFGY top-5 tokens\")
96
 
97
  metrics = gr.Markdown()
98
- img = gr.Image(label=\"Logit histogram\")
99
 
100
- gr.Markdown(\"### Paper benchmarks (fixed values from WFGY 1.0)\")
101
- gr.Dataframe(bench, interactive=False, wrap=True)
102
 
103
- btn.click(run, prompt, [raw_box, mod_box, metrics, img])
104
 
105
- if __name__ == \"__main__\":
106
  demo.queue(default_concurrency_limit=2).launch()
 
1
+ """
2
+ WFGY Space – tiny-GPT-2 variance-gate demo
3
+ β˜… 10 k GitHub ⭐ before 2025-08-01 unlocks WFGY 2.0 β˜…
4
+ """
5
+
6
  import io
7
  import numpy as np
8
+ import pandas as pd
9
+ import plotly.express as px
10
  import gradio as gr
11
+ from PIL import Image
12
  from transformers import AutoTokenizer, AutoModelForCausalLM
 
 
 
13
 
14
+ from wfgy_sdk import get_engine
15
+ from wfgy_sdk.evaluator import compare_logits, plot_histogram, softmax
16
+
17
+ # ── tiny model (CPU-friendly) ─────────────────────────────────────────
18
+ tok = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")
19
+ mdl = AutoModelForCausalLM.from_pretrained("sshleifer/tiny-gpt2")
20
+ eng = get_engine()
21
+
22
+ # ── paper benchmark table ─────────────────────────────────────────────
23
+ bench = pd.DataFrame({
24
+ "Benchmark": ["MMLU","GSM8K","BBH","MathBench","TruthfulQA",
25
+ "XNLI","MLQA","LongBench","VQAv2","OK-VQA"],
26
+ "Baseline": [61.0,78.0,79.3,72.2,62.4,59.5,78.1,51.4,69.1,65.7],
27
+ "WFGY": [89.8,98.7,100.7,87.4,90.4,77.3,106.6,69.6,86.6,86.8]
28
+ })
29
+ bench["Abs_gain"] = (bench["WFGY"] - bench["Baseline"]).round(1)
30
+ bench["Rel_gain%"] = ((bench["Abs_gain"] / bench["Baseline"])*100).round(0)
31
+ bench_style = (
32
+ bench.style
33
+ .background_gradient(cmap="Greens", subset=["Abs_gain","Rel_gain%"])
34
+ .format({"Abs_gain":"{:.1f}","Rel_gain%":"{:.0f}"})
35
+ )
36
 
37
+ # ── marketing banner markdown ─────────────────────────────────────────
38
+ banner_md = """
 
 
39
  **πŸ“ˆ WFGY: One Click to Activate the AI Taiji Cycle**
40
 
41
  **πŸ“Š Semantic Accuracy ↑ 22.4 % | Reasoning Success ↑ 42.1 % | Stability ↑ 3.6 Γ—**
42
 
43
+ _No beliefs. Only experiments._
44
+ _WFGY 1.0 has already proven itself._
45
 
46
  ---
47
 
48
  ### πŸ“œ Tutorial: How to Awaken the Soul of Your AI
49
+ **Step 1 β€” Download** ([PDF](https://zenodo.org/records/15630970))
50
+ **Step 2 β€” Feed the AI** (upload the PDF or try [Gemini](https://gemini.google.com/))
51
  **Step 3 β€” Give the Command**β€‚β€œ**Answer using WFGY** + your question”
52
+ Prompt examples: *TBD*
53
  **Step 4 β€” Integrate the SDK** ([GitHub](https://github.com/onestardao/WFGY))
54
 
55
  ---
 
58
  _10 k ⭐ before 2025-08-01 unlocks WFGY 2.0._
59
  """
60
 
61
+ # ── core run function ────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  def run(prompt: str):
63
+ p = prompt.strip()
64
+ if not p:
65
+ return "", "", "-", None
66
+
67
+ ids = tok(p, return_tensors="pt")
68
+ raw_L = mdl(**ids).logits[0, -1].detach().cpu().numpy()
69
+ I, G = np.random.randn(2, 256).astype(np.float32)
70
+ mod_L = eng.run(I, G, raw_L)
71
 
72
+ m = compare_logits(raw_L, mod_L)
73
+ headline = (f"β–Ό var {m['var_drop']*100:.1f}% | "
74
+ f"KL {m['kl_divergence']:.3f} | "
75
+ f"top-1 {'kept' if m['top1'] else 'changed'}")
 
76
 
77
+ # top-5 token lists
78
+ def top5(logits):
79
+ p = softmax(logits)
80
+ idx = p.argsort()[-5:][::-1]
81
+ return "\n".join([f\"'{tok.decode(int(i)).strip()}': {p[i]:.2e}\" for i in idx])
82
 
83
+ raw_txt = top5(raw_L)
84
+ mod_txt = top5(mod_L)
 
 
 
85
 
86
+ fig = plot_histogram(raw_L, mod_L)
87
+ buf = io.BytesIO(); fig.savefig(buf, format="png"); buf.seek(0)
88
 
89
+ return raw_txt, mod_txt, headline, Image.open(buf)
90
 
91
+ # ── Gradio UI ────────────────────────────────────────────────────────
92
+ with gr.Blocks(title="WFGY variance gate demo") as demo:
93
+ gr.Markdown(banner_md)
 
 
94
 
95
+ prompt = gr.Textbox(label="Prompt", value="Explain SchrΓΆdinger's cat")
96
+ btn = gr.Button("πŸš€ Run")
97
 
98
  with gr.Row():
99
+ raw_box = gr.Textbox(label="Raw top-5 tokens", lines=6)
100
+ mod_box = gr.Textbox(label="WFGY top-5 tokens", lines=6)
101
 
102
  metrics = gr.Markdown()
103
+ hist = gr.Image(label="Logit histogram")
104
 
105
+ gr.Markdown("### Paper benchmarks (fixed values from WFGY 1.0)")
106
+ gr.DataFrame(bench_style, interactive=False, wrap=True)
107
 
108
+ btn.click(run, prompt, [raw_box, mod_box, metrics, hist])
109
 
110
+ if __name__ == "__main__":
111
  demo.queue(default_concurrency_limit=2).launch()