billwang37 commited on
Commit
191bc56
·
verified ·
1 Parent(s): e10e3a2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -0
app.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import spaces
3
+ import torch
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ from peft import PeftModel
6
+ import os
7
+
8
+ BASE_MODEL = "Qwen/Qwen2.5-Math-7B-Instruct"
9
+ ADAPTER_REPO = "billwang37/mathbio-qwen-7b"
10
+ HF_TOKEN = os.environ.get("HF_TOKEN")
11
+
12
+ print("Loading tokenizer...")
13
+ tokenizer = AutoTokenizer.from_pretrained(ADAPTER_REPO, token=HF_TOKEN)
14
+
15
+ print("Loading base model...")
16
+ base_model = AutoModelForCausalLM.from_pretrained(
17
+ BASE_MODEL,
18
+ torch_dtype=torch.bfloat16,
19
+ device_map="auto",
20
+ )
21
+
22
+ print("Loading LoRA adapter...")
23
+ model = PeftModel.from_pretrained(base_model, ADAPTER_REPO, token=HF_TOKEN)
24
+ model.eval()
25
+ print("Model ready.")
26
+
27
+ SYSTEM_PROMPT = "You are MathBioAgent, an expert AI assistant specialized in mathematical biology, epidemiology, operator learning, and partial differential equations."
28
+
29
+ @spaces.GPU(duration=60)
30
+ def chat(message, history):
31
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}]
32
+ for h in history:
33
+ messages.append({"role": "user", "content": h[0]})
34
+ messages.append({"role": "assistant", "content": h[1]})
35
+ messages.append({"role": "user", "content": message})
36
+
37
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
38
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
39
+
40
+ with torch.no_grad():
41
+ outputs = model.generate(
42
+ **inputs,
43
+ max_new_tokens=1024,
44
+ temperature=0.3,
45
+ do_sample=True,
46
+ top_p=0.9,
47
+ )
48
+ response = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
49
+ return response
50
+
51
+ demo = gr.ChatInterface(
52
+ fn=chat,
53
+ title="MathBio AI — Mathematical Biology Assistant",
54
+ description="A specialized LLM for mathematical biology, epidemic modeling, PDEs, and operator learning. Fine-tuned on 27K arxiv-derived examples.",
55
+ examples=[
56
+ "What is R0 for an SIR model with beta=0.4 and gamma=0.1?",
57
+ "Derive the stability condition for the SEIR endemic equilibrium.",
58
+ "Explain the Keller-Segel chemotaxis model.",
59
+ ],
60
+ )
61
+
62
+ demo.launch()