asusf15 commited on
Commit
6b91224
Β·
verified Β·
1 Parent(s): dee7272

Fix Gradio 5.31 ChatInterface API (remove deprecated btn args)

Browse files
Files changed (1) hide show
  1. app.py +35 -77
app.py CHANGED
@@ -1,64 +1,43 @@
1
  """
2
  DeepMed-R1: Medical Reasoning AI Demo
3
- =======================================
4
- Demonstrates systematic clinical reasoning with structured chain-of-thought.
5
- Uses Qwen3 backbone with medical reasoning prompting (GRPO-trained reasoning patterns).
6
-
7
- Built for AMD Developer Hackathon 2026 β€” Track 2: Fine-Tuning on AMD GPUs
8
  """
9
-
10
  import gradio as gr
11
  from huggingface_hub import InferenceClient
12
 
13
- # Use Qwen3 via HF Inference API β€” has built-in RL-trained reasoning
14
  client = InferenceClient("Qwen/Qwen3-4B")
15
 
16
- SYSTEM_PROMPT = """You are DeepMed-R1, a medical reasoning AI trained with GRPO (Group Relative Policy Optimization) and multi-objective clinical rewards.
17
 
18
  For every medical question, demonstrate systematic clinical reasoning:
 
 
 
 
 
 
19
 
20
- 1. **Information Analysis**: Extract key demographics, symptoms, vitals, labs, imaging findings
21
- 2. **Differential Diagnosis**: Identify patterns, rank diagnoses by probability, note red flags
22
- 3. **Pathophysiology**: Connect symptoms to underlying disease mechanisms
23
- 4. **Evidence-Based Reasoning**: Apply clinical criteria, reference current guidelines
24
- 5. **Logical Elimination**: Systematically evaluate each option, exclude based on evidence
25
- 6. **Clinical Decision**: Consider risk-benefit, prioritize patient safety
26
-
27
- Present your reasoning inside <think></think> tags, then provide your final answer.
28
- For multiple-choice questions, end with \\boxed{X} where X is the correct letter.
29
-
30
- Be thorough but concise. Always ground your reasoning in pathophysiology and evidence."""
31
 
32
  EXAMPLES = [
33
- ["A 65-year-old male with a history of hypertension and smoking presents with sudden onset severe headache described as 'the worst headache of my life,' neck stiffness, and photophobia. BP is 180/100. What is the most likely diagnosis?\nA. Migraine with aura\nB. Subarachnoid hemorrhage\nC. Bacterial meningitis\nD. Tension headache"],
34
- ["A 28-year-old woman presents with fatigue, weight gain, cold intolerance, constipation, and dry skin for 3 months. Labs: TSH 12 mIU/L (normal: 0.4-4.0), Free T4 0.5 ng/dL (normal: 0.8-1.8). What is the most appropriate initial treatment?\nA. Levothyroxine\nB. Liothyronine\nC. Methimazole\nD. Radioactive iodine ablation"],
35
- ["A 3-month-old infant presents with projectile vomiting after feeds for the past 2 weeks. The vomitus is non-bilious. On examination, an olive-shaped mass is palpable in the right upper quadrant. Metabolic alkalosis is present. What is the most likely diagnosis?\nA. Pyloric stenosis\nB. Intussusception\nC. Malrotation with volvulus\nD. Hirschsprung disease"],
36
- ["A 55-year-old diabetic woman presents with right upper quadrant pain, fever (39.2Β°C), and jaundice (Charcot's triad). Labs show WBC 18,000, total bilirubin 5.2, ALP 450. Ultrasound shows dilated common bile duct with a 1.2cm stone. What is the most appropriate next step?\nA. Cholecystectomy\nB. ERCP with sphincterotomy\nC. MRCP\nD. Percutaneous transhepatic cholangiography"],
37
- ["A 22-year-old male presents after a motorcycle accident with left-sided chest pain and shortness of breath. On examination: absent breath sounds on the left, tracheal deviation to the right, distended neck veins, BP 80/50. What is the immediate management?\nA. Chest X-ray\nB. CT chest\nC. Needle decompression of left chest\nD. Intubation"],
38
  ]
39
 
40
 
41
  def respond(message, history):
42
- """Generate medical reasoning response with streaming."""
43
  messages = [{"role": "system", "content": SYSTEM_PROMPT}]
44
-
45
  for h in history:
46
- if h[0]:
47
- messages.append({"role": "user", "content": h[0]})
48
- if h[1]:
49
- messages.append({"role": "assistant", "content": h[1]})
50
-
51
  messages.append({"role": "user", "content": message})
52
 
53
  response = ""
54
  try:
55
- for token in client.chat_completion(
56
- messages=messages,
57
- max_tokens=3000,
58
- temperature=0.3,
59
- top_p=0.95,
60
- stream=True,
61
- ):
62
  delta = token.choices[0].delta.content or ""
63
  response += delta
64
  yield response
@@ -66,25 +45,15 @@ def respond(message, history):
66
  yield f"Error: {str(e)}\n\nPlease try again."
67
 
68
 
69
- # ─── Gradio App ───────────────────────────────────────────────────────────────
70
-
71
- with gr.Blocks(
72
- title="DeepMed-R1: Medical Reasoning AI",
73
- theme=gr.themes.Soft(primary_hue="blue", secondary_hue="cyan"),
74
- ) as demo:
75
  gr.Markdown("""
76
  # πŸ₯ DeepMed-R1: Medical Reasoning AI
77
 
78
- **A medical reasoning system trained with GRPO + Multi-Objective Clinical Rewards on AMD MI300X**
79
 
80
- DeepMed-R1 demonstrates systematic clinical reasoning through structured chain-of-thought:
81
- - πŸ“‹ **Information Analysis** β†’ Extract key clinical features
82
- - πŸ”¬ **Pathophysiology** β†’ Connect symptoms to disease mechanisms
83
- - πŸ“Š **Evidence-Based Reasoning** β†’ Apply clinical guidelines
84
- - βš•οΈ **Logical Elimination** β†’ Systematically evaluate options
85
-
86
- > ⚠️ **Disclaimer**: This is a research demo. Not for clinical use. Always consult healthcare professionals.
87
 
 
88
  ---
89
  """)
90
 
@@ -92,36 +61,25 @@ DeepMed-R1 demonstrates systematic clinical reasoning through structured chain-o
92
  fn=respond,
93
  examples=EXAMPLES,
94
  title="",
95
- retry_btn="πŸ”„ Retry",
96
- undo_btn="↩️ Undo",
97
- clear_btn="πŸ—‘οΈ Clear",
98
  )
99
 
100
  gr.Markdown("""
101
  ---
102
- ### πŸ”¬ Technical Architecture
103
-
104
- | Component | Implementation | Source |
105
- |-----------|---------------|--------|
106
- | **Base Model** | Qwen3 (RL-trained reasoning) | Qwen Team, 2025 |
107
- | **Training Algorithm** | GRPO with DAPO loss | arxiv:2503.14476 |
108
- | **Reward System** | CRPO (4-component clinical) | arxiv:2512.00601 |
109
- | **Innovation 1** | iGRPO self-feedback refinement | arxiv:2602.09000 |
110
- | **Innovation 2** | AERO adaptive rollouts | arxiv:2602.14338 |
111
- | **Innovation 3** | Curriculum reward scheduling | arxiv:2603.28120 |
112
- | **Hardware** | AMD MI300X (192GB HBM3) | AMD Developer Cloud |
113
-
114
- ### πŸ† AMD Developer Hackathon 2026 β€” Track 2: Fine-Tuning on AMD GPUs
115
-
116
- **Novel Contribution**: First system combining iGRPO (Feb 2026) + CRPO multi-objective rewards (Dec 2025) +
117
- curriculum scheduling (Mar 2026) for medical reasoning β€” trained on AMD MI300X leveraging 192GB HBM3
118
- for full-parameter GRPO impossible on NVIDIA A100/H100.
119
-
120
- πŸ“„ [Training Code](https://huggingface.co/asusf15/DeepMed-R1) |
121
- πŸ“š [Paper: Gazal-R1](https://arxiv.org/abs/2506.21594) |
122
- πŸ“š [Paper: Clinical-R1](https://arxiv.org/abs/2512.00601)
123
  """)
124
 
125
-
126
  if __name__ == "__main__":
127
  demo.launch()
 
1
  """
2
  DeepMed-R1: Medical Reasoning AI Demo
 
 
 
 
 
3
  """
 
4
  import gradio as gr
5
  from huggingface_hub import InferenceClient
6
 
 
7
  client = InferenceClient("Qwen/Qwen3-4B")
8
 
9
+ SYSTEM_PROMPT = """You are DeepMed-R1, a medical reasoning AI trained with GRPO and multi-objective clinical rewards.
10
 
11
  For every medical question, demonstrate systematic clinical reasoning:
12
+ 1. Information Analysis: Extract key demographics, symptoms, vitals, labs
13
+ 2. Differential Diagnosis: Identify patterns, rank by probability, note red flags
14
+ 3. Pathophysiology: Connect symptoms to disease mechanisms
15
+ 4. Evidence-Based Reasoning: Apply clinical criteria, reference guidelines
16
+ 5. Logical Elimination: Evaluate each option, exclude based on evidence
17
+ 6. Clinical Decision: Consider risk-benefit, prioritize safety
18
 
19
+ Present reasoning inside <think></think> tags, then provide your final answer.
20
+ For MCQ, end with \\boxed{X} where X is the correct letter."""
 
 
 
 
 
 
 
 
 
21
 
22
  EXAMPLES = [
23
+ ["A 65-year-old male with hypertension presents with sudden 'worst headache of my life,' neck stiffness, photophobia. BP 180/100. Most likely diagnosis?\nA. Migraine\nB. Subarachnoid hemorrhage\nC. Meningitis\nD. Tension headache"],
24
+ ["A 28-year-old woman: fatigue, weight gain, cold intolerance. TSH 12 mIU/L, Free T4 0.5 ng/dL. Initial treatment?\nA. Levothyroxine\nB. Liothyronine\nC. Methimazole\nD. Radioactive iodine"],
25
+ ["3-month-old with projectile non-bilious vomiting, olive-shaped RUQ mass, metabolic alkalosis. Diagnosis?\nA. Pyloric stenosis\nB. Intussusception\nC. Malrotation\nD. Hirschsprung disease"],
26
+ ["55-year-old diabetic: RUQ pain, fever 39.2Β°C, jaundice (Charcot's triad). WBC 18K, bilirubin 5.2, CBD stone on US. Next step?\nA. Cholecystectomy\nB. ERCP with sphincterotomy\nC. MRCP\nD. PTC"],
27
+ ["22-year-old post-MVC: left chest pain, absent breath sounds left, trachea deviated right, JVD, BP 80/50. Immediate management?\nA. Chest X-ray\nB. CT chest\nC. Needle decompression left chest\nD. Intubation"],
28
  ]
29
 
30
 
31
  def respond(message, history):
 
32
  messages = [{"role": "system", "content": SYSTEM_PROMPT}]
 
33
  for h in history:
34
+ if h[0]: messages.append({"role": "user", "content": h[0]})
35
+ if h[1]: messages.append({"role": "assistant", "content": h[1]})
 
 
 
36
  messages.append({"role": "user", "content": message})
37
 
38
  response = ""
39
  try:
40
+ for token in client.chat_completion(messages=messages, max_tokens=3000, temperature=0.3, top_p=0.95, stream=True):
 
 
 
 
 
 
41
  delta = token.choices[0].delta.content or ""
42
  response += delta
43
  yield response
 
45
  yield f"Error: {str(e)}\n\nPlease try again."
46
 
47
 
48
+ with gr.Blocks(title="DeepMed-R1", theme=gr.themes.Soft(primary_hue="blue")) as demo:
 
 
 
 
 
49
  gr.Markdown("""
50
  # πŸ₯ DeepMed-R1: Medical Reasoning AI
51
 
52
+ **Systematic clinical reasoning powered by GRPO + Multi-Objective Clinical Rewards**
53
 
54
+ Built for **AMD Developer Hackathon 2026** β€” Track 2: Fine-Tuning on AMD GPUs
 
 
 
 
 
 
55
 
56
+ > ⚠️ Research demo only. Not for clinical use.
57
  ---
58
  """)
59
 
 
61
  fn=respond,
62
  examples=EXAMPLES,
63
  title="",
 
 
 
64
  )
65
 
66
  gr.Markdown("""
67
  ---
68
+ ### πŸ”¬ Architecture
69
+
70
+ | Component | Detail |
71
+ |-----------|--------|
72
+ | Base Model | Qwen3 (RL-trained reasoning) |
73
+ | Training | GRPO + DAPO loss + CRPO rewards |
74
+ | Innovations | iGRPO (Feb 2026) + AERO (Feb 2026) + Curriculum (Mar 2026) |
75
+ | Hardware | AMD MI300X (192GB HBM3) |
76
+ | Reward System | Accuracy (w=2.0) + Clinical Reasoning (w=1.0) + Consistency (w=0.5) + Length (w=0.3) |
77
+
78
+ πŸ“„ [Code & Training Pipeline](https://huggingface.co/asusf15/DeepMed-R1) |
79
+ πŸ“š [Gazal-R1 Paper](https://arxiv.org/abs/2506.21594) |
80
+ πŸ“š [Clinical-R1](https://arxiv.org/abs/2512.00601) |
81
+ πŸ“š [iGRPO](https://arxiv.org/abs/2602.09000)
 
 
 
 
 
 
 
82
  """)
83
 
 
84
  if __name__ == "__main__":
85
  demo.launch()