import jsonimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizerfrom peft import PeftModel BASE_MODEL_NAME = "Qwen/Qwen2.5-1.5B-Instruct"ADAPTER_REPO_ID = "Bhupati1998/BioEvidence-LLM-1.5B" # 1. Load Tokenizer & Base Modeltokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_NAME, trust_remote_code=True)base_model = AutoModelForCausalLM.from_pretrained( BASE_MODEL_NAME, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, device_map="auto" if torch.cuda.is_available() else None, trust_remote_code=True,) # 2. Attach Trained LoRA Adaptermodel = PeftModel.from_pretrained(base_model, ADAPTER_REPO_ID)model.eval() # 3. Define Biomedical Question & Evidence Contextquestion = "Does statin therapy reduce 30-day cardiovascular mortality in patients with type 2 diabetes?"context = ( "BACKGROUND: Cardiovascular events represent the primary source of excess mortality in diabetic patients. " "METHODS: In a multi-center randomized controlled trial of 1,200 diabetic adults, subjects were assigned to daily atorvastatin 20mg or placebo. " "RESULTS: At 30 days, cardiovascular mortality was 2.8% in the atorvastatin arm versus 5.1% in the placebo arm (hazard ratio 0.54, 95% CI 0.38-0.78, p=0.002). " "CONCLUSIONS: Statin therapy significantly reduces short-term cardiovascular mortality in diabetic adults.") # 4. Format Prompt with System Instructionmessages = [ { "role": "system", "content": ( "You are BioEvidence-LLM, a specialized biomedical evidence-grounded AI. " "Analyze the biomedical question strictly based on the provided evidence context. " "Output your answer ONLY as a valid JSON object with the keys: decision, answer, evidence, uncertainty, limitations." ), }, { "role": "user", "content": f"Evidence Context:\n{context}\n\nQuestion: {question}", },] prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)inputs = tokenizer(prompt, return_tensors="pt").to(model.device) # 5. Generate Grounded JSON Responsewith torch.no_grad(): outputs = model.generate(**inputs, max_new_tokens=256, temperature=0.1, do_sample=False) response_text = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)print(response_text)