Views
No views yet

"Restoring the 'Think' in Medical AI."
| Model Region | Source Model | Role | Weights |
|---|---|---|---|
| Foundation (Layers 0-8) | Llama-3.1-Instruct | Syntax, instruction following, and grammar stability. | 100% |
| Logic Core (Layers 8-20) | Hermes-3 + Llama-3.1 | Clinical Reasoning: Implicit logic and causal analysis. | 45% Hermes / 55% Base |
| Medical Cortex (Layers 20-28) | Aloe-Beta + Llama-3.1 | Knowledge Retrieval: High-density injection of medical textbooks and guidelines. | 52% Aloe / 48% Base |
| Frontal Cortex (Layers 28-32) | Llama-3.1-Instruct | Safety & Output: Ensures polite, structured, and compliant responses. | 100% |
| Model | Size | Inference Method | MedQA (USMLE) | MMLU-Medical | MedMCQA |
|---|---|---|---|---|---|
| Avicenna-8B-Base | 8B | Self-Consistency (SC) (N=5) | 61.0% | - | 50.0% |
| Avicenna-8B-Base | 8B | Greedy | 60.0% | 69.5% | - |
| GPT-3.5 Turbo | 175B+ | Standard | 61.2% | 73.5% | 59.4% |
| ClinicalCamel-70B | 70B | Standard | 45.8% | 68.4% | 45.8% |
| PMC-LLaMA-13B | 13B | Standard | 39.6% | 56.3% | 37.7% |
| MedAlpaca-13B | 13B | Standard | 37.3% | 51.5% | 35.7% |
| BioMistral-7B | 7B | Standard | 35.4% | 52.6% | 34.8% |
| Meditron-7B | 7B | Standard | 33.5% | 45.2% | 31.1% |
Methodology Notes:
- Hardware: All results obtained using 4-bit NF4 Quantization on NVIDIA T4 GPUs. Full precision scores are expected to be higher.
- Inference: MedQA and MedMCQA utilized Self-Consistency Ensembling (SC) inference (N=5 voters). MMLU utilized standard Greedy decoding.
- Sampling: MedQA and MedMCQA results represent randomized subsets of the validation/test sets due to compute constraints. MMLU represents the complete evaluation of all 6 medical subsets.
1import torch
2from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
3
4# --- CONFIGURATION ---
5MODEL_ID = "salihfurkaan/Avicenna-8B-Base"
6TOKENIZER_ID = "meta-llama/Meta-Llama-3.1-8B-Instruct"
7
8def setup_model():
9 print(f"Loading {MODEL_ID} in 4-bit mode...")
10
11 bnb_config = BitsAndBytesConfig(
12 load_in_4bit=True,
13 bnb_4bit_compute_dtype=torch.float16,
14 bnb_4bit_use_double_quant=True,
15 bnb_4bit_quant_type="nf4"
16 )
17
18 tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_ID)
19 if tokenizer.pad_token is None:
20 tokenizer.pad_token = tokenizer.eos_token
21
22 model = AutoModelForCausalLM.from_pretrained(
23 MODEL_ID,
24 quantization_config=bnb_config, # you can remove this line if you want the non-quantized version
25 device_map="auto"
26 )
27 return model, tokenizer
28
29def solve_with_moa_open_ended(model, tokenizer, user_input):
30 """
31 Runs Mixture-of-Agents for open-ended queries:
32 1. Generates 3 distinct clinical opinions (Drafts).
33 2. Synthesizes them into a final consensus answer.
34 """
35
36 # --- PHASE 1: DRAFTING (3 Internal Specialists) ---
37 system_prompt_draft = "You are Avicenna, an expert medical consultant. Analyze the case step-by-step. Provide a Differential Diagnosis and Recommended Next Steps."
38
39 messages = [{"role": "system", "content": system_prompt_draft}, {"role": "user", "content": user_input}]
40 inputs = tokenizer.apply_chat_template(messages, return_tensors="pt", add_generation_prompt=True).to(model.device)
41
42 print("Consulting 3 internal specialists (Drafting Phase)...")
43
44 with torch.no_grad():
45 outputs = model.generate(
46 **inputs,
47 max_new_tokens=1536,
48 temperature=0.7, # High creativity for diverse perspectives
49 do_sample=True,
50 num_return_sequences=3, # Generate 3 Drafts
51 pad_token_id=tokenizer.eos_token_id
52 )
53
54 # Extract only the new tokens (answers) from the output
55 # outputs shape: [3, seq_len]
56 # inputs shape: [1, seq_len] -> We slice off the prompt length
57 new_tokens = outputs[:, inputs.input_ids.shape[1]:]
58 drafts = tokenizer.batch_decode(new_tokens, skip_special_tokens=True)
59
60 # --- PHASE 2: SYNTHESIS (Chief Resident) ---
61 print(" Synthesizing Final Consensus...")
62
63 combined_drafts = ""
64 for i, draft in enumerate(drafts):
65 combined_drafts += f"\n[Opinion {i+1}]:\n{draft}\n"
66 # Optional: Print drafts to see the internal debate
67 # print(f"\n--- Opinion {i+1} ---\n{draft[:200]}...")
68
69 aggregator_prompt = (
70 f"Clinical Case:\n{user_input}\n\n"
71 f"Consider the following 3 medical opinions on this case:\n{combined_drafts}\n\n"
72 "TASK: Synthesize these opinions into a single, highly accurate, and professional clinical assessment. "
73 "Resolve any conflicts by prioritizing patient safety and standard of care. "
74 "Structure the answer clearly: 1. Assessment, 2. Key Differentials, 3. Plan."
75 )
76
77 agg_messages = [
78 {"role": "system", "content": "You are a Senior Chief Physician. Provide a final authoritative consultation."},
79 {"role": "user", "content": aggregator_prompt}
80 ]
81
82 agg_inputs = tokenizer.apply_chat_template(agg_messages, return_tensors="pt", add_generation_prompt=True).to(model.device)
83
84 with torch.no_grad():
85 final_output = model.generate(
86 **agg_inputs,
87 max_new_tokens=768,
88 temperature=0.2, # Low temp for stable synthesis
89 do_sample=True,
90 pad_token_id=tokenizer.eos_token_id
91 )
92
93 final_response = tokenizer.decode(final_output[0][agg_inputs.input_ids.shape[1]:], skip_special_tokens=True)
94 return final_response
95
96if __name__ == "__main__":
97 # Initialize
98 model, tokenizer = setup_model()
99
100 print("\n Avicenna Interactive Consultant")
101 print("Type 'exit' or 'quit' to stop.\n")
102
103 while True:
104 print("\n" + "-"*30)
105 question = input("Enter Clinical Case/Question: ")
106 if question.lower() in ["exit", "quit"]:
107 break
108
109 final_answer = solve_with_moa_open_ended(model, tokenizer, question)
110
111 print("\n" + "="*40)
112 print(f"FINAL CLINICAL CONSENSUS")
113 print("="*40)
114 print(final_answer)