Spaces:
Runtime error
Runtime error
Math Fast Agent (Phi) pinned & streaming
Browse files
app.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os, torch, gradio as gr
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer, BitsAndBytesConfig
|
| 4 |
+
|
| 5 |
+
TITLE = os.getenv("SPACE_TITLE", "LanguageBridge — Math Fast Agent (Phi-3.5)")
|
| 6 |
+
MODEL_ID = os.getenv("MODEL_ID", "microsoft/phi-3.5-mini-instruct")
|
| 7 |
+
|
| 8 |
+
SYSTEM = (
|
| 9 |
+
"你是數學與規則推理助教。原則:"
|
| 10 |
+
"1) 先『列出必要步驟』;2) 再給『最終答案』;3) 嚴禁瞎掰,資訊不足要明說。"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
def load_llm():
|
| 14 |
+
bnb = BitsAndBytesConfig(
|
| 15 |
+
load_in_4bit=True, bnb_4bit_quant_type="nf4",
|
| 16 |
+
bnb_4bit_use_double_quant=True,
|
| 17 |
+
bnb_4bit_compute_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float16
|
| 18 |
+
)
|
| 19 |
+
kwargs = dict(device_map="auto", quantization_config=bnb, trust_remote_code=False)
|
| 20 |
+
try:
|
| 21 |
+
model = AutoModelForCausalLM.from_pretrained(MODEL_ID, **kwargs)
|
| 22 |
+
except Exception as e:
|
| 23 |
+
print("[4-bit failed] → fallback:", e)
|
| 24 |
+
kwargs.pop("quantization_config", None)
|
| 25 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 26 |
+
MODEL_ID,
|
| 27 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 28 |
+
device_map="auto" if torch.cuda.is_available() else None,
|
| 29 |
+
trust_remote_code=False
|
| 30 |
+
)
|
| 31 |
+
tok = AutoTokenizer.from_pretrained(MODEL_ID, use_fast=True)
|
| 32 |
+
if tok.pad_token is None: tok.pad_token = tok.eos_token
|
| 33 |
+
tok.padding_side = "left"
|
| 34 |
+
if torch.cuda.is_available():
|
| 35 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 36 |
+
model.config.use_cache = True
|
| 37 |
+
return tok, model
|
| 38 |
+
|
| 39 |
+
tokenizer, llm = load_llm(); llm.eval()
|
| 40 |
+
|
| 41 |
+
def format_prompt(q:str)->str:
|
| 42 |
+
return f"{SYSTEM}\n\n題目:{q}\n請照原則作答:"
|
| 43 |
+
|
| 44 |
+
@torch.inference_mode()
|
| 45 |
+
def stream_answer(q, mx=192, temp=0.1, top_p=0.9):
|
| 46 |
+
prompt = format_prompt(q)
|
| 47 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(llm.device)
|
| 48 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 49 |
+
gen = dict(
|
| 50 |
+
**inputs, streamer=streamer, max_new_tokens=int(mx),
|
| 51 |
+
temperature=float(temp), top_p=float(top_p),
|
| 52 |
+
do_sample=True if float(temp)>0 else False,
|
| 53 |
+
eos_token_id=tokenizer.eos_token_id, pad_token_id=tokenizer.pad_token_id
|
| 54 |
+
)
|
| 55 |
+
import threading
|
| 56 |
+
t = threading.Thread(target=llm.generate, kwargs=gen); t.start()
|
| 57 |
+
buf=""
|
| 58 |
+
for tok in streamer:
|
| 59 |
+
buf += tok
|
| 60 |
+
yield buf
|
| 61 |
+
|
| 62 |
+
def warmup():
|
| 63 |
+
try:
|
| 64 |
+
_ = list(stream_answer("π 的前三位有效數字?", mx=32))[-1]
|
| 65 |
+
print("[warmup] done")
|
| 66 |
+
except Exception as e:
|
| 67 |
+
print("[warmup] skip:", e)
|
| 68 |
+
|
| 69 |
+
with gr.Blocks(title=TITLE, theme="soft") as demo:
|
| 70 |
+
gr.Markdown(f"## {TITLE}\n模型:`{MODEL_ID}`|建議:短題短答、先步驟後答案(已流式)")
|
| 71 |
+
q = gr.Textbox(label="數學題 / 規則題(可貼LaTeX)", placeholder="例:f(x)=(x^2+1)e^x 求 f'(x)", lines=3)
|
| 72 |
+
mx = gr.Slider(64, 512, value=192, step=32, label="max_new_tokens")
|
| 73 |
+
temp = gr.Slider(0.0, 0.8, value=0.1, step=0.05, label="temperature")
|
| 74 |
+
top = gr.Slider(0.6, 1.0, value=0.9, step=0.01, label="top_p")
|
| 75 |
+
go = gr.Button("計算 🚀", variant="primary")
|
| 76 |
+
out= gr.Textbox(label="逐步輸出", lines=14)
|
| 77 |
+
clr= gr.Button("清除")
|
| 78 |
+
|
| 79 |
+
go.click(stream_answer, inputs=[q, mx, temp, top], outputs=out)
|
| 80 |
+
clr.click(lambda:"", outputs=out)
|
| 81 |
+
|
| 82 |
+
demo.queue()
|
| 83 |
+
warmup()
|
| 84 |
+
|
| 85 |
+
if __name__ == "__main__":
|
| 86 |
+
demo.launch(share=False, server_name="0.0.0.0", server_port=7860, show_error=True)
|