panikos commited on
Commit
00350d6
·
verified ·
1 Parent(s): 52e3179

Upload test_production_model_comprehensive.py with huggingface_hub

Browse files
test_production_model_comprehensive.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # dependencies = ["transformers>=4.40.0", "peft>=0.7.0", "bitsandbytes>=0.41.0", "accelerate>=0.28.0"]
3
+ # ///
4
+
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
6
+ from peft import PeftModel
7
+ import torch
8
+
9
+ print("=" * 80)
10
+ print("COMPREHENSIVE BIOMEDICAL MODEL EVALUATION")
11
+ print("=" * 80)
12
+ print("\nModel: panikos/llama-biomedical-production-qlora")
13
+ print("Training: 17,008 examples, 1 epoch, QLoRA")
14
+ print("=" * 80)
15
+
16
+ print("\n[1/3] Loading base model with 4-bit quantization...")
17
+ bnb_config = BitsAndBytesConfig(
18
+ load_in_4bit=True,
19
+ bnb_4bit_use_double_quant=True,
20
+ bnb_4bit_quant_type="nf4",
21
+ bnb_4bit_compute_dtype=torch.bfloat16
22
+ )
23
+
24
+ base_model = AutoModelForCausalLM.from_pretrained(
25
+ "meta-llama/Llama-3.1-8B-Instruct",
26
+ quantization_config=bnb_config,
27
+ device_map="auto"
28
+ )
29
+
30
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
31
+ tokenizer.pad_token = tokenizer.eos_token
32
+ print(" Base model loaded")
33
+
34
+ print("\n[2/3] Loading production LoRA adapters...")
35
+ model = PeftModel.from_pretrained(
36
+ base_model,
37
+ "panikos/llama-biomedical-production-qlora"
38
+ )
39
+ print(" LoRA adapters loaded")
40
+
41
+ print("\n[3/3] Running comprehensive evaluation...")
42
+ print("=" * 80)
43
+
44
+ # Test cases covering various biomedical scenarios
45
+ test_cases = [
46
+ {
47
+ "name": "Simple LOINC to SDTM Mapping",
48
+ "prompt": "Map the following LOINC code to CDISC SDTM domain:\n\nLOINC: 2339-0 (Glucose [Mass/volume] in Blood)",
49
+ "expected_keywords": ["LB", "Laboratory"]
50
+ },
51
+ {
52
+ "name": "Complex LOINC Panel Classification",
53
+ "prompt": """Analyze the following LOINC codes and classify each into the appropriate CDISC SDTM domain:
54
+
55
+ 1. 2339-0: Glucose [Mass/volume] in Blood
56
+ 2. 4548-4: Hemoglobin A1c/Hemoglobin.total in Blood
57
+ 3. 2160-0: Creatinine [Mass/volume] in Serum or Plasma
58
+
59
+ Also identify if they form a panel and specify clinical significance.""",
60
+ "expected_keywords": ["LB", "Laboratory", "metabolic", "diabetes", "renal"]
61
+ },
62
+ {
63
+ "name": "CDISC Terminology Query",
64
+ "prompt": "What is the CDISC SDTM terminology for patient-reported adverse event severity?",
65
+ "expected_keywords": ["AESEV", "severity", "adverse event"]
66
+ },
67
+ {
68
+ "name": "Adverse Event Classification",
69
+ "prompt": "Classify the following observation into the appropriate SDTM domain:\n\nPatient reported experiencing headache with severity of moderate, lasting 2 hours after taking study medication.",
70
+ "expected_keywords": ["AE", "Adverse", "Event"]
71
+ },
72
+ {
73
+ "name": "SDTM vs ADaM Knowledge",
74
+ "prompt": "Explain the difference between SDTM and ADaM in CDISC standards.",
75
+ "expected_keywords": ["SDTM", "ADaM", "source", "analysis"]
76
+ },
77
+ {
78
+ "name": "Vital Signs Mapping",
79
+ "prompt": "Map the following LOINC code to CDISC SDTM domain:\n\nLOINC: 8867-4 (Heart rate)",
80
+ "expected_keywords": ["VS", "Vital", "Signs"]
81
+ }
82
+ ]
83
+
84
+ results = []
85
+ for i, test in enumerate(test_cases, 1):
86
+ print(f"\n{'='*80}")
87
+ print(f"TEST {i}/{len(test_cases)}: {test['name']}")
88
+ print(f"{'='*80}")
89
+ print(f"\nPrompt: {test['prompt'][:100]}...")
90
+
91
+ # Format prompt
92
+ messages = [{"role": "user", "content": test['prompt']}]
93
+
94
+ # Tokenize
95
+ input_ids = tokenizer.apply_chat_template(
96
+ messages,
97
+ add_generation_prompt=True,
98
+ return_tensors="pt"
99
+ ).to(model.device)
100
+
101
+ # Generate
102
+ print("\n>>> Model Response:")
103
+ print("-" * 80)
104
+ with torch.no_grad():
105
+ outputs = model.generate(
106
+ input_ids,
107
+ max_new_tokens=250,
108
+ temperature=0.7,
109
+ top_p=0.9,
110
+ do_sample=True,
111
+ pad_token_id=tokenizer.eos_token_id
112
+ )
113
+
114
+ # Decode
115
+ response = tokenizer.decode(outputs[0][input_ids.shape[1]:], skip_special_tokens=True)
116
+ print(response)
117
+ print("-" * 80)
118
+
119
+ # Evaluate
120
+ found_keywords = [kw for kw in test['expected_keywords'] if kw.lower() in response.lower()]
121
+ score = (len(found_keywords) / len(test['expected_keywords'])) * 100
122
+
123
+ print(f"\n>>> Evaluation:")
124
+ print(f"Expected keywords: {', '.join(test['expected_keywords'])}")
125
+ print(f"Found: {', '.join(found_keywords) if found_keywords else 'None'}")
126
+ print(f"Score: {score:.0f}% ({len(found_keywords)}/{len(test['expected_keywords'])})")
127
+
128
+ results.append({
129
+ 'name': test['name'],
130
+ 'score': score,
131
+ 'found': len(found_keywords),
132
+ 'total': len(test['expected_keywords'])
133
+ })
134
+
135
+ # Overall evaluation
136
+ print("\n" + "=" * 80)
137
+ print("OVERALL EVALUATION SUMMARY")
138
+ print("=" * 80)
139
+
140
+ avg_score = sum(r['score'] for r in results) / len(results)
141
+ total_found = sum(r['found'] for r in results)
142
+ total_expected = sum(r['total'] for r in results)
143
+
144
+ print(f"\nAverage Score: {avg_score:.1f}%")
145
+ print(f"Total Keywords Found: {total_found}/{total_expected}")
146
+ print(f"\nIndividual Test Results:")
147
+ for r in results:
148
+ print(f" {r['name']}: {r['score']:.0f}% ({r['found']}/{r['total']})")
149
+
150
+ print("\n" + "=" * 80)
151
+ if avg_score >= 70:
152
+ print("RESULT: EXCELLENT - Model shows strong biomedical understanding")
153
+ print("RECOMMENDATION: Model is ready for production use!")
154
+ elif avg_score >= 50:
155
+ print("RESULT: GOOD - Model has solid biomedical knowledge")
156
+ print("RECOMMENDATION: Consider additional training for edge cases")
157
+ else:
158
+ print("RESULT: NEEDS IMPROVEMENT - Consider additional training epochs")
159
+
160
+ print("=" * 80)