# -*- coding: utf-8 -*- """Word-problem reader Space: Qwen3-8B (ZeroGPU) reads an English word problem into Spiral information sentences with the team's v7 prompt -> program brain (Python, CPU) solves -> hand-wired left brain computes the prefix. Written by: Claude subagent (讀題 Space), 2026-11-27.""" import json import os import random import threading import time import gradio as gr import spaces import torch from transformers import AutoModelForCausalLM, AutoTokenizer import pipeline MODEL = "Qwen/Qwen3-8B" tok = AutoTokenizer.from_pretrained(MODEL) model = AutoModelForCausalLM.from_pretrained(MODEL, torch_dtype=torch.bfloat16) model.to("cuda") @spaces.GPU(duration=120) def generate(prompt): """One greedy read, thinking off (same settings as the team's offline comparison).""" text = tok.apply_chat_template([{"role": "user", "content": prompt}], tokenize=False, add_generation_prompt=True, enable_thinking=False) enc = tok([text], return_tensors="pt").to("cuda") with torch.no_grad(): out = model.generate(**enc, max_new_tokens=pipeline.MAX_NEW_TOKENS, do_sample=False) return tok.decode(out[0, enc["input_ids"].shape[1]:], skip_special_tokens=True) # ---------------------------------------------------------------- program brain (CPU) + hand-wired left brain pipeline.init() import mixer # noqa: E402 (#348 逐句混合: loads spaCy en_core_web_sm + the pickled construction reader) mixer.init() _LB ={"fn": None, "err": None} _lb_lock = threading.Lock() _lb_ready = threading.Event() def _load_lb(): try: import core # HandWired-LeftBrain-1 v0.4 package (downloaded from the Hub) core.init() core._solve_inner("What is 2 + 3?") def lb(q): with _lb_lock: # the network code is not thread-safe return core._solve_inner(q) _LB["fn"] = lb except Exception as e: # noqa: BLE001 _LB["err"] = f"{type(e).__name__}: {e}"[:200] _lb_ready.set() threading.Thread(target=_load_lb, daemon=True).start() # ---------------------------------------------------------------- data DATA = json.load(open(os.path.join(os.path.dirname(__file__), "data", "problems.json"), encoding="utf-8")) RANDOM_TYPE = "隨機抽題型 Random type" LABELS = [t["label"] for t in DATA["types"]] BY_Q = {" ".join(x["question"].split()): (x, t["label"]) for t in DATA["types"] for x in t["items"]} N_ITEMS = len(BY_Q) _RULE = json.load(open(os.path.join(os.path.dirname(__file__), "data", "rule_layer_coverage.json"), encoding="utf-8")) RULE_N = _RULE["讀出"] RULE_DETAIL = f"對 {_RULE['對']}、錯 {_RULE['錯']};實跑 read/solve 統計,{_RULE['日期']}" def random_question(kind): types = DATA["types"] if kind in (None, "", RANDOM_TYPE) else [t for t in DATA["types"] if t["label"] == kind] t = random.choice(types or DATA["types"]) x = random.choice(t["items"]) return x["question"], f"🎲 {t['label']}|{x['id']}(GSM8K train 開發題,有標答;按「送出」開始讀題)", "" # ---------------------------------------------------------------- formatting def _code(lines): return "```\n" + ("\n".join(lines) if lines else "(none)") + "\n```" def _vars(rows): out = [] for r in rows or []: out.append(" ".join(f"{k}: {v}" for k, v in r.items()) if isinstance(r, dict) else str(r)) return out def layer_md(r): if r["layer"] == "程式": return ("**走哪一層:第一層 程式讀題**(規則樹讀題,沒有呼叫 Qwen,不會背題)。Layer 1, rule-tree reader: no model call.") if r["layer"] == "模型": return f"**走哪一層:第二層 {r['layer_label']}**。程式層拒因 rule-layer refusal:{r['rule_why'] or '-'}" return "**走哪一層:-**" def trace_md(r, ref): s = [layer_md(r)] if r["layer"] == "模型" and r["rule_lines"]: s += ["程式層讀到的資訊句(沒讀完,拒答)rule-layer sentences:", _code(r["rule_lines"])] if r.get("repair"): rp = r["repair"] s += [f"### 讀法修補 Reading repair (#350): {'、'.join(rp['動作'])}", f"修補前拒因 before: {rp['修補前拒因']}", "修補前資訊句 before:", _code(r.get("lines_before_repair") or []), "證據 evidence:", _code(rp["證據"])] mx = r.get("mix") if mx: rows = [] for p in mx: if "錯誤" in p: rows.append(f"逐句混合失敗(照用模型讀法):{p['錯誤']}") continue tag = "程式讀" if p["來源"] == "程式" else "模型讀" line = f"#{p['句號']} [{tag}]" + (f" 構式 {'、'.join(p['構式'])}" if p.get("構式") else "") if p["來源"] == "程式": kept = p.get("守門留下") or [] prog = p["程式讀"][:len(p["程式讀"]) - len(kept)] # mixer puts program lines first, kept model lines after line += "\n 程式讀 program: " + (" | ".join(prog) or "(空:程式認為這句沒有要記的數)") line += "\n 模型原本 model: " + (" | ".join(p["模型讀"]) or "(none)") if p.get("守門留下"): line += "\n 取代守門留下的模型行(不屬於這句)kept: " + " | ".join(p["守門留下"]) elif p.get("備註"): line += f"({p['備註']})" rows.append(line) n = sum(1 for p in mx if p.get("來源") == "程式") s += [f"### 逐句混合 Per-sentence mix (#348):{n} 句程式讀、其餘模型讀", _code("\n".join(rows).split("\n"))] fb = r.get("feedback") if fb: s += ["### 🔧 回饋修正 Feedback correction (#350 v1, same Qwen3-8B)" + ("(成功)" if fb["status"] == "ok" else "(仍拒答)")] if fb.get("錯誤"): s += [f"錯誤 error: {fb['錯誤']}"] if not fb["rounds"]: s += ["(沒有進行:程式產生不出指正,或一讀前的修補已通過)"] for h in fb["rounds"]: s += [f"第 {h['回合']} 回合 round {h['回合']} 程式指正原文 program's feedback:", _code(h["指正"].split("\n")), "模型改後的行 model's rewritten lines:", _code((h["模型改後"] or "(empty)").split("\n")), f"→ {'答 ' + str(h['value']) if h['status'] == 'ok' else '拒答:' + str(h['拒答原因'])}" + (f"(另經修補 {'、'.join(h['修補'])})" if h.get("修補") else "") + (f";丟掉沒被指出的句號的行:{h['越界行']}" if h.get("越界行") else "")] s += ["### 耗時 Seconds", "\n".join(["| 階段 stage | 秒 s |", "|---|---|"] + [f"| {k} | {v} |" for k, v in r["seconds"].items()])] s += ["### 1. 斷句 Sentences", _code([f"#{i} {x}" for i, x in enumerate(r["sentences"], 1)]), "### 2. 讀題器原始回覆 Reader reply (Qwen3-8B, v7 prompt, greedy, thinking off)", _code([r["reply"]] if r["reply"] else []), "### 3. 資訊句 Information sentences (after the reader's own checks)", _code(r["lines"]), "### 4. 解析結果 Parsed (中文式螺旋語)", _code(r["parsed"] if isinstance(r["parsed"], list) else str(r["parsed"] or "").split("\n")), "### 5. 程式腦 Program brain", f"狀態 status: `{r['brain_status'] or '-'}`", "變數表 variables:", _code(_vars(r["variables"])), "方程 equations:", _code(r["equations"])] if r["teaching"]: s += ["步驟 steps:", _code(r["teaching"])] s += [f"前綴 prefix: `{r['prefix'] or '-'}` 程式腦精確值 exact value: `{r['brain_value'] or '-'}`", "### 6. 左腦 Left brain (hand-wired threshold networks)", _code(r["lb_steps"])] if r["notes"]: s += ["註記 notes:", _code(r["notes"])] if r["stuck"] or r["refusal"]: s += ["### 拒答 Refusal", f"原因 reason: {r['refusal']}", _code(r["stuck"])] if ref: s += ["### 參考 Reference (not this run): DeepSeek v7 reading of the same question, which the current brain answers correctly", _code(ref["deepseek_v7_lines"])] return "\n\n".join(s) def answer_text(r, ref): if r["answer"] is not None: head = f"答案 Answer: {r['answer']}" else: head = "拒答 Refused(不猜)" lines = [head, f"讀題層 layer: {r['layer_label'] or '-'}"] if ref is not None: mark = {"✓": "✓ 對 correct", "✗": "✗ 錯 wrong", "拒答": "拒答 refused"}[r["verdict"]] lines.append(f"判分 {mark} (標答 reference: {ref['gold']})") else: lines.append("(自己打的題目,沒有標答 no reference answer)") if r["answer"] is None: lines.append("原因 reason: " + (r["refusal"] or r["status"])) if r["stuck"]: lines.append("卡在 stuck at: " + r["stuck"][0]) else: lines.append(r["status"]) lines.append(f"耗時 {r['seconds'].get('合計 total')} s") return "\n".join(lines) FEEDBACK_ROUNDS = 1 def solve(question, feedback=False): q = " ".join((question or "").split()) hit = BY_Q.get(q) ref = hit[0] if hit else None _lb_ready.wait(timeout=90) r = pipeline.solve(q, generate, _LB["fn"], gold=ref["gold"] if ref else None, pid=ref["id"] if ref else "user", feedback=bool(feedback), rounds=FEEDBACK_ROUNDS) if _LB["fn"] is None and r["lb_steps"]: r["lb_steps"] = r["lb_steps"] + [f"(左腦沒載入:{_LB['err'] or 'still loading'};以上都由 Python 分數計算)"] return answer_text(r, ref), trace_md(r, ref), "" _MARK = {"✓": "✓", "✗": "✗", "拒答": "拒", None: "-"} def _short(r): a = f"答 {r['answer']}" if r["answer"] is not None else "拒答(" + (r["refusal"] or r["status"])[:80] + ")" return f"[{r['layer_label'] or '-'}] {a}" def solve_vary(question, feedback=False): """🔀 換數字再讀: read the question as is, then a copy with new Arabic integers (word numbers unchanged).""" q = " ".join((question or "").split()) hit = BY_Q.get(q) ref = hit[0] if hit else None v = pipeline.variant(q, ref["deepseek_v7_lines"] if ref else None, random.Random()) _lb_ready.wait(timeout=90) fbk = dict(feedback=bool(feedback), rounds=FEEDBACK_ROUNDS) r1 = pipeline.solve(q, generate, _LB["fn"], gold=ref["gold"] if ref else None, pid=ref["id"] if ref else "user", **fbk) if not v["question"]: msg = (f"換數字失敗(試 {v['tries']} 次):{v['why']}\n只讀了原題 {_short(r1)}" + (f",判分 {_MARK[r1['verdict']]}(標答 {ref['gold']})" if ref else "")) return msg, trace_md(r1, ref), "" r2 = pipeline.solve(v["question"], generate, _LB["fn"], gold=v["gold"], pid=(ref["id"] + "-a") if ref else "user-a", **fbk) mp = "、".join(f"{pipeline._fs(a)}→{pipeline._fs(b)}" for a, b in v["map"].items()) if ref: head = f"原題 {_MARK[r1['verdict']]}|換數字 {_MARK[r2['verdict']]}" if r1["verdict"] == "✓" and r2["verdict"] == "✓": head += " → 會讀(非背題)" + ("(兩次都是程式讀題)" if r1["layer"] == r2["layer"] == "程式" else "") elif r1["verdict"] == "✓": head += " → 原題對、換數字沒對:可能背過題" lines = [head, f"原題:{_short(r1)}(標答 {ref['gold']})", f"換數字:{_short(r2)}(新標答 {v['gold']},程式腦用參考讀法重算)"] else: lines = ["自打題沒有標答,兩次讀法並排:", f"原題:{_short(r1)}", f"換數字:{_short(r2)}"] lines += [f"換的數字 numbers changed: {mp}(英文數字詞不改;試 {v['tries']} 次)", f"換數字後的題目:{v['question']}", f"耗時 {r1['seconds'].get('合計 total')} + {r2['seconds'].get('合計 total')} s"] t1 = "## 原題 Original\n\n" + trace_md(r1, ref) t2 = "## 換數字 New numbers\n\n" + f"題目:{v['question']}\n\n" + trace_md(r2, None) return "\n".join(lines), t1, t2 # ---------------------------------------------------------------- page INTRO = ("# 英文應用題讀題 Word-problem reader\n" "兩層讀題:先用**程式讀題**(規則樹,不會背題);程式讀不出才交 **Qwen3-8B** 寫螺旋語資訊句(再過讀法修補)→ " "**程式腦**(Python)列式求解 → **手搓左腦**(手填權重的門檻網路)算前綴;讀不懂就拒答並指出卡在哪一句,不猜。" "Rule-tree reader first, Qwen3-8B only when it cannot read; the program brain solves, the hand-wired left brain " "does the arithmetic; it refuses instead of guessing.") NOTES = f""" --- ## 說明 About **兩層 Two layers.** - **第一層 程式讀題**:`規則樹/資訊句輸出.py`(規則樹選葉子寫資訊句,沒有模型)。程式讀的題不會背題,換數字照樣讀。 但涵蓋目前**很小**:GSM8K train 開發題(範圍守門過濾後)**7,066 題只讀出 {RULE_N} 題**({RULE_DETAIL});每加一條規則就會變多。 - **第二層 模型讀題**:程式讀不出才交 Qwen3-8B;一讀被擋下時再試 #350 讀法修補器(預設開 R1 缺單位補位、R3 引用對齊;R2、R4 關), 所有成功的修補候選答案相同才放行,不新增原文沒有的數字或角色。回答框標「模型讀題(已修補 R?)」或「(未修補)」。 **模型層要換數字還對才算**(模型可能看過 GSM8K train)。 - **逐句混合(#348,預設開)**:Qwen 讀完後,凡是原子句構式在放行表(31 種)的事實句,改用程式讀法(構式讀題器:spaCy 解壓成原子句、照構式填槽)取代 Qwen 那句;取代守門 keep:Qwen 寫在這句、但數字或主詞/物名不屬於這句的行會留下。問句和其他句 保留 Qwen,之後再走修補。跑的過程區逐句標「程式讀/模型讀」。168 題 Qwen 已存回覆重放:對錯拒 11/7/150 與純 Qwen 相同 (程式取代 69 句);團隊 DeepSeek 驗收集只換放行表時 99.0% 不變、變錯 0。 - **🔧 回饋修正(#350 v1,開關,預設關)**:修補後仍拒答時,程式指出哪幾句有問題(句號+原文+那句的行+問題+該詞格式), 請**同一個 Qwen3-8B** 只重寫那幾句(來回 1 次);改完重跑全部守門,其他句號的行一律丟掉。團隊量測(修正模型是另一個免費模型 GLM-5.3-flash,不是這裡的 Qwen): 救 16/新錯 5,換數字 41 件 對 13/錯 0;Qwen 當修正模型的開/關對照還沒量,量完淨正才會改成預設開。開了會多一次 GPU 呼叫。 - Layer 1 rule-tree reader covers only {RULE_N} of 7,066 GSM8K-train dev questions today and grows with each rule; layer 2 (Qwen3-8B + #350 repair) only counts if it still reads correctly with new numbers. **誠實數字 Honest numbers.** Qwen3-8B 零樣本 v7 讀法,在 168 題 GSM8K train 開發題對照:**對 10、錯 7、拒 151**; 同題 DeepSeek v7 單讀 **19/5/144**。所以這裡大多數題目會拒答,這是預期的。團隊主讀題器用 DeepSeek(付費 API,不在這個 Space)。 數字是團隊自己量的,未經第三方驗證。On 168 GSM8K-train development questions Qwen3-8B (zero-shot, v7 prompt) got 10 right, 7 wrong, 151 refused; a single DeepSeek v7 read of the same questions got 19 / 5 / 144. Self-reported, not independently verified. **隨機題 Random questions.** {N_ITEMS} 題,{len(LABELS)} 類,來自 GSM8K **train**(開發題;保留題、固定驗收題已用範圍守門排除;沒有用 GSM8K test)。 挑的是「DeepSeek v7 讀法+現在的程式腦答對」的題,所以 Qwen 讀錯或拒答的原因多半在讀題,不在程式腦。題型是依資訊句概念與題目關鍵字自動分的,可能有分錯。 自己打的題目也可以,只是沒有標答。 **🔀 換數字再讀 New numbers.** 模型可能看過 GSM8K train(背過題),**換數字還讀對才算**。按鈕把題目裡的阿拉伯整數換成不同的新整數(英文數字詞 two/twice/half/three times 不改),原題和新題各讀一次。 題庫題的新標答:把 DeepSeek 參考讀法裡的數字照同一對位換掉,交程式腦重算;算不出或不是正整數就重抽,最多 5 次(離線試 480 題,約 70% 換得出)。兩次都對才寫「會讀(非背題)」。 The model may have seen GSM8K train; a reading only counts if it still works with new numbers. **做法 How it works.** 1. 斷句後,v7 提示(約 {pipeline.prompt_chars():,} 字的概念表、規則與例子)+編號句子送給 Qwen3-8B(ZeroGPU,bf16,貪婪解碼,`enable_thinking=False`,最多 {pipeline.MAX_NEW_TOKENS} 個新 token)。單題約 8~11 秒(加上 ZeroGPU 排隊)。 2. 回覆逐句轉成英文式資訊句,例 `have(reggie, usd, 48, start).`、`ask(have(reggie, usd, ?, now)).`;格式不對的句子標「未讀」。 3. 程式腦(`程式腦.py`,CPU)把資訊句接成積木與方程、精確求解,輸出螺旋語前綴(例 `減 48 乘 2 5`)。 4. 守門:資訊句裡的字面數沒用到、資訊句沒用到(抽掉測試)、非整數答案、語意守門、v7 守門 → 拒答。解析器遇到畸形輸出無限遞迴也算拒答。 5. 前綴逐步交給手搓左腦([Bigbearbo/handwired-left-brain-1](https://huggingface.co/Bigbearbo/handwired-left-brain-1) v0.4)算整數加減乘除;左腦不收的(非整數、單位換算)標「Python 分數計算」。每一步也跟 Python 對照。 **限制 Limits.** 模型層只讀一次(不做第二讀);上面 10/7/151 是沒有程式層、沒有讀法修補時量的;一次只服務一位使用者;ZeroGPU 有每日 GPU 配額,排隊時會比較慢。程式腦是團隊共用區 2026-11-27 的版本複本(`hs/`),之後主線更新不會自動同步。 **授權 License.** 本 Space 程式與資料 cc-by-nc-4.0;Qwen3-8B 是 Apache-2.0(Qwen team);GSM8K 是 MIT(OpenAI)。 """ with gr.Blocks(title="Word-problem reader") as demo: gr.Markdown(INTRO) with gr.Group(): with gr.Row(equal_height=True): question = gr.Textbox(label="題目 Question (English)", lines=7, scale=3, placeholder="Type an English word problem, or press 🎲 for a random one.") answer = gr.Textbox(label="回答 Answer", lines=7, scale=2, interactive=False) with gr.Row(equal_height=True): kind = gr.Dropdown([RANDOM_TYPE] + LABELS, value=RANDOM_TYPE, label="題型 Question type", scale=3) dice = gr.Button("🎲 隨機出題 Random question", scale=1) go = gr.Button("送出 Solve", variant="primary", scale=1) vary = gr.Button("🔀 換數字再讀 New numbers", scale=1) fbk = gr.Checkbox(value=False, label="🔧 程式指正後讓模型再改一次 Let the model fix the lines the program points out (1 round)") picked = gr.Markdown("") with gr.Accordion("跑的過程 Pipeline trace", open=True): with gr.Row(): trace = gr.Markdown("(送出後顯示:資訊句、解析結果、程式腦方程、左腦每一步、耗時)") trace2 = gr.Markdown("") gr.Markdown(NOTES) dice.click(random_question, inputs=kind, outputs=[question, picked, answer], api_name="random") go.click(solve, inputs=[question, fbk], outputs=[answer, trace, trace2], api_name="solve") vary.click(solve_vary, inputs=[question, fbk], outputs=[answer, trace, trace2], api_name="vary") question.submit(solve, inputs=[question, fbk], outputs=[answer, trace, trace2], api_name=False) demo.queue(default_concurrency_limit=1).launch(show_error=True)