MohamedAhmedAE commited on
Commit
7804e97
·
verified ·
1 Parent(s): 5023c17

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +309 -34
README.md CHANGED
@@ -1,58 +1,333 @@
1
  ---
 
2
  base_model: meta-llama/Llama-3.2-3B-Instruct
3
- library_name: transformers
4
- model_name: Llama-3.2-3B-Instruct-Medical-Finetune-v5
 
 
5
  tags:
6
- - generated_from_trainer
7
- - trl
8
- - sft
9
- licence: license
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  ---
11
 
12
- # Model Card for Llama-3.2-3B-Instruct-Medical-Finetune-v5
13
 
14
- This model is a fine-tuned version of [meta-llama/Llama-3.2-3B-Instruct](https://huggingface.co/meta-llama/Llama-3.2-3B-Instruct).
15
- It has been trained using [TRL](https://github.com/huggingface/trl).
 
 
16
 
17
- ## Quick start
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  ```python
20
- from transformers import pipeline
 
 
 
 
 
21
 
22
- question = "If you had a time machine, but could only go to the past or the future once and never return, which would you choose and why?"
23
- generator = pipeline("text-generation", model="MohamedAhmedAE/Llama-3.2-3B-Instruct-Medical-Finetune-v5", device="cuda")
24
- output = generator([{"role": "user", "content": question}], max_new_tokens=128, return_full_text=False)[0]
25
- print(output["generated_text"])
26
  ```
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  ## Training procedure
29
 
30
- [<img src="https://raw.githubusercontent.com/wandb/assets/main/wandb-github-badge-28.svg" alt="Visualize in Weights & Biases" width="150" height="24"/>](https://wandb.ai/mohamed-ahmed/Llama-3.2-3B-Instruct-Medical-Finetune-v5/runs/44aemw1g)
 
 
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- This model was trained with SFT.
 
 
 
34
 
35
- ### Framework versions
36
 
37
- - TRL: 0.21.0
38
- - Transformers: 4.55.4
39
- - Pytorch: 2.8.0
40
- - Datasets: 3.6.0
41
- - Tokenizers: 0.21.4
42
 
43
- ## Citations
 
 
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
- Cite TRL as:
48
-
49
  ```bibtex
50
- @misc{vonwerra2022trl,
51
- title = {{TRL: Transformer Reinforcement Learning}},
52
- author = {Leandro von Werra and Younes Belkada and Lewis Tunstall and Edward Beeching and Tristan Thrush and Nathan Lambert and Shengyi Huang and Kashif Rasul and Quentin Gallou{\'e}dec},
53
- year = 2020,
54
- journal = {GitHub repository},
55
- publisher = {GitHub},
56
- howpublished = {\url{https://github.com/huggingface/trl}}
 
 
 
 
57
  }
58
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ license: llama3.2
3
  base_model: meta-llama/Llama-3.2-3B-Instruct
4
+ library_name: peft
5
+ pipeline_tag: text-generation
6
+ language:
7
+ - en
8
  tags:
9
+ - medical
10
+ - healthcare
11
+ - clinical
12
+ - clinical-decision-support
13
+ - question-answering
14
+ - medical-qa
15
+ - llama
16
+ - llama-3.2
17
+ - lora
18
+ - qlora
19
+ - peft
20
+ - parameter-efficient-fine-tuning
21
+ - 4-bit
22
+ datasets:
23
+ - MohamedAhmedAE/Med_LLaMa3_fine-tuning_dataset
24
+ - medalpaca/medical_meadow_medqa
25
+ - medalpaca/medical_meadow_medical_flashcards
26
+ - medalpaca/medical_meadow_wikidoc
27
+ - medalpaca/medical_meadow_wikidoc_patient_information
28
+ - medalpaca/medical_meadow_cord19
29
+ - medalpaca/medical_meadow_pubmed_causal
30
+ - openlifescienceai/medmcqa
31
+ - bigbio/med_qa
32
+ - qiaojin/PubMedQA
33
+ - deepset/covid_qa_deepset
34
  ---
35
 
36
+ # Med-LLaMA3.2-3BMedical QLoRA Adapter (LoRA weights only)
37
 
38
+ > Parameter-efficient medical adaptation of **Llama-3.2-3B** using **QLoRA** (4-bit NF4 + LoRA).
39
+ > This repository contains the **LoRA adapter only** — it must be applied on top of the base
40
+ > model at load time. For a ready-to-use, standalone checkpoint, see the **merged** version
41
+ > linked below.
42
 
43
+ This is the **3B (balanced / mid-tier)** member of the **Med-LLaMA3** family introduced in the paper
44
+ *“Med-LLaMA3: Advancing Medical Question-Answering Through Parameter-Efficient Fine-Tuning of Large
45
+ Language Models”* (Applied Sciences, 2026). The family adapts the LLaMA-3 architecture to the medical
46
+ domain by training only a small fraction of the base model’s parameters (**5.70% for this 3B variant**),
47
+ achieving strong medical question-answering performance while reducing memory use by roughly **75%** via
48
+ 4-bit quantization — enabling development and inference on low-cost, consumer-grade hardware.
49
+
50
+ The 3B variant offers a **balanced trade-off between computational efficiency and capacity** — a
51
+ competitive mid-tier option with meaningfully better accuracy than the 1B and lower compute than the 8B.
52
+
53
+ - 📄 **Paper:** [Med-LLaMA3 (Applied Sciences 2026, 16(12), 6158)](https://www.mdpi.com/2076-3417/16/12/6158) · DOI: [10.3390/app16126158](https://doi.org/10.3390/app16126158)
54
+ - 💻 **Code:** [github.com/Mohamed-Ahmed-Abo-El-Enen/MasterPapers](https://github.com/Mohamed-Ahmed-Abo-El-Enen/MasterPapers)
55
+ - 🧩 **Merged (standalone) version:** [`MohamedAhmedAE/Llama-3.2-3B-Instruct-Medical-Finetuned-merged`](https://huggingface.co/MohamedAhmedAE/Llama-3.2-3B-Instruct-Medical-Finetuned-merged)
56
+
57
+ ---
58
+
59
+ ## Model details
60
+
61
+ | | |
62
+ |---|---|
63
+ | **Base model** | [`meta-llama/Llama-3.2-3B-Instruct`](https://huggingface.co/meta-llama/Llama-3.2-3B-Instruct) |
64
+ | **Adaptation method** | QLoRA — 4-bit **NF4** quantization (double quantization) + LoRA |
65
+ | **LoRA rank (`r`)** | 128 |
66
+ | **LoRA alpha (`α`)** | 256 (scaling `α/r = 2.0`) |
67
+ | **LoRA target modules** | All linear layers — `q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj` |
68
+ | **Trainable parameters** | 194.51 M LoRA parameters = **5.70%** of the 3.40 B total (base weights frozen) |
69
+ | **Compute dtype** | bfloat16 (mixed precision) |
70
+ | **Architecture** | 28 decoder layers · hidden size 3072 · intermediate size 8192 · GQA (24 query heads, 8 KV heads) |
71
+ | **Context window** | 128K tokens (inherited from base) |
72
+ | **Vocabulary** | 128,256 tokens |
73
+ | **Language** | English |
74
+ | **License** | [Llama 3.2 Community License](https://github.com/meta-llama/llama-models/blob/main/models/llama3_2/LICENSE) |
75
+
76
+ > **ℹ️ Base checkpoint.** A LoRA adapter only loads correctly onto the *exact* base model it was trained
77
+ > on. This adapter targets the **instruct** checkpoint `meta-llama/Llama-3.2-3B-Instruct` (consistent
78
+ > with the released fine-tuned model). Use that same base in the code below.
79
+
80
+ ---
81
+
82
+ ## Intended uses
83
+
84
+ **Primary use cases**
85
+
86
+ - Medical **question answering** (multiple-choice and open-ended).
87
+ - Clinical knowledge lookup and **clinical decision support** assistance.
88
+ - A balanced mid-tier option when the 1B is too small and the 8B is too heavy.
89
+ - A research baseline for parameter-efficient fine-tuning of small LLaMA models in healthcare.
90
+
91
+ **Out of scope / not intended for**
92
+
93
+ - Autonomous clinical decision-making or direct patient care without a qualified clinician in the loop.
94
+ - Generating definitive diagnoses, prescriptions, or treatment plans.
95
+ - Use as a substitute for professional medical advice, emergency services, or licensed care.
96
+
97
+ See **[Limitations & responsible use](#limitations--responsible-use)** before any applied use.
98
+
99
+ ---
100
+
101
+ ## How to use
102
+
103
+ This is a PEFT/LoRA adapter, so you load the **base model first** and then attach the adapter.
104
+
105
+ ```bash
106
+ pip install -U transformers peft accelerate bitsandbytes torch
107
+ ```
108
+
109
+ ### Option A — 4-bit inference (lower GPU memory)
110
+
111
+ ```python
112
+ import torch
113
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
114
+ from peft import PeftModel
115
+
116
+ BASE_MODEL = "meta-llama/Llama-3.2-3B-Instruct"
117
+ ADAPTER = "MohamedAhmedAE/Llama-3.2-3B-Instruct-Medical-Finetuned" # <-- this adapter repo
118
+
119
+ bnb_config = BitsAndBytesConfig(
120
+ load_in_4bit=True,
121
+ bnb_4bit_quant_type="nf4",
122
+ bnb_4bit_use_double_quant=True,
123
+ bnb_4bit_compute_dtype=torch.bfloat16,
124
+ )
125
+
126
+ tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
127
+ base = AutoModelForCausalLM.from_pretrained(
128
+ BASE_MODEL,
129
+ quantization_config=bnb_config,
130
+ device_map="auto",
131
+ )
132
+ model = PeftModel.from_pretrained(base, ADAPTER)
133
+ model.eval()
134
+
135
+ messages = [
136
+ {"role": "system", "content": "You are a knowledgeable medical assistant. Answer accurately and concisely."},
137
+ {"role": "user", "content": "What is the first-line treatment for uncomplicated community-acquired pneumonia in a healthy adult?"},
138
+ ]
139
+ inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
140
+
141
+ with torch.no_grad():
142
+ out = model.generate(inputs, max_new_tokens=256, do_sample=False, temperature=0.0)
143
+ print(tokenizer.decode(out[0][inputs.shape[-1]:], skip_special_tokens=True))
144
+ ```
145
+
146
+ ### Option B — full-precision inference
147
 
148
  ```python
149
+ import torch
150
+ from transformers import AutoModelForCausalLM, AutoTokenizer
151
+ from peft import PeftModel
152
+
153
+ BASE_MODEL = "meta-llama/Llama-3.2-3B-Instruct"
154
+ ADAPTER = "MohamedAhmedAE/Llama-3.2-3B-Instruct-Medical-Finetuned"
155
 
156
+ tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
157
+ base = AutoModelForCausalLM.from_pretrained(BASE_MODEL, torch_dtype=torch.bfloat16, device_map="auto")
158
+ model = PeftModel.from_pretrained(base, ADAPTER)
 
159
  ```
160
 
161
+ ### Optional — merge the adapter into the base
162
+
163
+ If you want a single standalone model (no PEFT dependency at inference), merge the weights:
164
+
165
+ ```python
166
+ merged = model.merge_and_unload()
167
+ merged.save_pretrained("Med-LLaMA3.2-3B-Medical-merged")
168
+ tokenizer.save_pretrained("Med-LLaMA3.2-3B-Medical-merged")
169
+ ```
170
+
171
+ *(A pre-merged checkpoint is also published separately — see the link at the top of this card.)*
172
+
173
+ ---
174
+
175
+ ## Training data
176
+
177
+ The Med-LLaMA3 family was fine-tuned on a curated **medical instruction dataset of over 1.5 million
178
+ samples**, organized along a three-axis taxonomy: **source type** (examination QA, clinical dialogue,
179
+ biomedical literature, encyclopedic reference) × **clinical granularity** (basic science, clinical
180
+ reasoning, patient communication) × **task format** (multiple-choice, open-ended QA, generative
181
+ dialogue). All sources were consolidated into a unified instruction–response schema
182
+ (`system`, `context`, `question`, `answer`, `choices`).
183
+
184
+ Sources include:
185
+
186
+ - **MedAlpaca / Medical Meadow** collection — MEDIQA, Medical Flashcards, WikiDoc, WikiDoc Patient
187
+ Information, MedQA, CORD-19, and PubMed Causal subsets
188
+ - **MedMCQA** — Indian medical entrance exam (AIIMS & NEET PG) multiple-choice questions
189
+ - **MedQA-USMLE** — USMLE-style 4-option multiple-choice questions (English)
190
+ - **BigBIO MedQA** — standardized biomedical QA
191
+ - **PubMedQA** — research questions over PubMed abstracts (yes/no/maybe)
192
+ - **COVID-QA (deepset)** — COVID-19 / SARS-CoV-2 question answering
193
+ - **MedQuAD** — consumer-health QA compiled from authoritative NIH sources
194
+ - **HealthCareMagic** — real-world patient–doctor conversation transcripts
195
+
196
+ The data-cleaning and corpus-assembly scripts are released in the
197
+ [code repository](https://github.com/Mohamed-Ahmed-Abo-El-Enen/MasterPapers), and the final compiled
198
+ fine-tuning dataset is available at
199
+ [`MohamedAhmedAE/Med_LLaMa3_fine-tuning_dataset`](https://huggingface.co/datasets/MohamedAhmedAE/Med_LLaMa3_fine-tuning_dataset).
200
+
201
+ > **Evaluation integrity:** The eight **MMLU medical subsets** were used **only for held-out
202
+ > evaluation** and were **excluded** from the fine-tuning corpus. For benchmarks with official splits
203
+ > (MedMCQA, MedQA-USMLE, PubMedQA), only the official **training** partitions were used for fine-tuning.
204
+
205
+ ---
206
+
207
  ## Training procedure
208
 
209
+ LoRA and optimization settings are identical across the 1B, 3B, and 8B variants; sequence length, batch
210
+ size, and gradient accumulation are scaled to each model’s memory footprint. The settings below are for
211
+ the **3B** variant.
212
 
213
+ | Setting | Value (3B) |
214
+ |---|---|
215
+ | Method | QLoRA (4-bit NF4 base, LoRA adapters in higher precision) |
216
+ | LoRA `r` / `α` / dropout / bias | 128 / 256 / 0.05 / none |
217
+ | Target modules | All linear layers (q, k, v, o, gate, up, down) |
218
+ | Trainable params | 194.51 M (5.70% of 3.40 B) |
219
+ | Quantization | 4-bit NF4 with double quantization (bitsandbytes) |
220
+ | Optimizer | Paged AdamW 8-bit (β₁ = 0.9, β₂ = 0.999), weight decay 0.1 |
221
+ | Learning rate / schedule | 2.0 × 10⁻⁵ / cosine annealing, 5 warmup steps |
222
+ | Epochs | 5 |
223
+ | Max sequence length | 2048 |
224
+ | Batch size / grad accumulation | 4 per device / 16 steps |
225
+ | Max gradient norm | 1.0 |
226
+ | Precision & memory | bfloat16 · gradient checkpointing · DeepSpeed ZeRO-2 · FlashAttention-2 |
227
+ | Hardware | 2 × NVIDIA RTX 4050 (12 GB), ~30 days |
228
+ | Experiment tracking | Weights & Biases |
229
 
230
+ The QLoRA recipe keeps the base weights frozen and quantized, allocating optimizer state only for the
231
+ LoRA parameters — which is what makes fine-tuning feasible on consumer hardware.
232
+
233
+ ---
234
 
235
+ ## Evaluation
236
 
237
+ Evaluation in the paper uses the **EleutherAI LM Evaluation Harness** with **5-shot** prompting on the
238
+ eight MMLU medical subsets (Anatomy, Clinical Knowledge, College Biology, College Medicine, Medical
239
+ Genetics, Nutrition, Professional Medicine, Virology). Reported comparisons include **McNemar’s test**
240
+ p-values and **95% bootstrap confidence intervals**.
 
241
 
242
+ The table below reports the 3B model’s 5-shot accuracy (%) on each MMLU medical subset, with 95%
243
+ bootstrap confidence intervals (1000 resamples), as published in Table 7 of the paper. For context, the
244
+ family’s mean accuracy scales with model size: **1B = 48.64%**, **3B = 64.24%**, **8B = 75.71%**.
245
 
246
+ | MMLU medical subset (5-shot) | Med-LLaMA3.2-3B (acc. %) |
247
+ |---|---|
248
+ | Anatomy | 59.52 (±4.26) |
249
+ | Clinical Knowledge | 68.17 (±2.89) |
250
+ | College Biology | 71.53 (±3.77) |
251
+ | College Medicine | 57.65 (±3.78) |
252
+ | Medical Genetics | 75.00 (±4.35) |
253
+ | Nutrition | 68.32 (±2.69) |
254
+ | Professional Medicine | 70.59 (±2.77) |
255
+ | Virology | 43.17 (±3.84) |
256
+ | **Mean (8 subsets)** | **64.24** |
257
+
258
+ > The paper reports an untuned baseline only for the 8B model (vs. `Llama-3.1-8B-Instruct`); it does
259
+ > **not** include an untuned `Llama-3.2-3B` baseline on these subsets. See Table 7 of the paper for the
260
+ > full cross-model comparison (1B, 8B, and other ≤8B models) with statistical tests.
261
+
262
+ See the [paper](https://www.mdpi.com/2076-3417/16/12/6158) for full tables, statistical tests, and
263
+ confidence intervals.
264
+
265
+ ---
266
 
267
+ ## Limitations & responsible use
268
+
269
+ - **Not a medical device.** This model is a research artifact. It must **not** be used for autonomous
270
+ diagnosis, treatment, prescribing, or any decision affecting patient care without review by a
271
+ qualified healthcare professional.
272
+ - **Hallucination risk.** Like all LLMs, it can produce fluent but incorrect or fabricated medical
273
+ information. Always verify outputs against authoritative sources.
274
+ - **Mid-tier capacity.** The 3B is a balanced variant; for the highest accuracy on complex clinical
275
+ reasoning, prefer the 8B variant when resources allow. For the smallest footprint, the 1B is available.
276
+ - **Abbreviation ambiguity.** Medical abbreviations are a known error source. The paper’s safety pilot
277
+ shows that **context-disambiguation preprocessing** reduces the highest-severity abbreviation
278
+ errors (from 30% to 10% on a held-out set); consider applying similar preprocessing.
279
+ - **Data & bias.** Training data may under-represent certain populations, conditions, or regional
280
+ practices, and may encode biases present in the source corpora.
281
+ - **Privacy & compliance.** Do not input protected health information (PHI) unless your deployment is
282
+ appropriately secured and compliant with applicable regulations (e.g., HIPAA, GDPR).
283
+ - **English only.** Performance outside English is not evaluated.
284
+
285
+ ---
286
+
287
+ ## License
288
+
289
+ This adapter is released under the **[Llama 3.2 Community License](https://github.com/meta-llama/llama-models/blob/main/models/llama3_2/LICENSE)**,
290
+ inherited from the base model. By using it you agree to Meta’s Llama 3.2 license terms and
291
+ Acceptable Use Policy. Review the licenses of the individual training datasets for any additional
292
+ restrictions on derived use.
293
+
294
+ ---
295
+
296
+ ## Citation
297
+
298
+ If you use this model, please cite the paper:
299
 
 
 
300
  ```bibtex
301
+ @article{aboelenen2026medllama3,
302
+ title = {Med-LLaMA3: Advancing Medical Question-Answering Through Parameter-Efficient Fine-Tuning of Large Language Models},
303
+ author = {Abo El-Enen, Mohamed Ahmed and Ismail, Sally S. and Nazmy, Taymoor Mohamed},
304
+ journal = {Applied Sciences},
305
+ volume = {16},
306
+ number = {12},
307
+ pages = {6158},
308
+ year = {2026},
309
+ publisher = {MDPI},
310
+ doi = {10.3390/app16126158},
311
+ url = {https://www.mdpi.com/2076-3417/16/12/6158}
312
  }
313
+ ```
314
+
315
+ ## Authors & contact
316
+
317
+ Mohamed Ahmed Abo El-Enen, Sally S. Ismail, and Taymoor Mohamed Nazmy
318
+ Faculty of Computer and Information Sciences, Ain Shams University, Cairo, Egypt.
319
+
320
+ ---
321
+
322
+ ## Model family
323
+
324
+ | Variant | Type | Repository |
325
+ |---|---|---|
326
+ | Med-LLaMA3.2-1B | Adapter | [`MohamedAhmedAE/Llama-3.2-1B-Instruct-Medical-Finetuned`](https://huggingface.co/MohamedAhmedAE/Llama-3.2-1B-Instruct-Medical-Finetuned) |
327
+ | Med-LLaMA3.2-1B | Merged | [`MohamedAhmedAE/Llama-3.2-1B-Instruct-Medical-Finetuned-merged`](https://huggingface.co/MohamedAhmedAE/Llama-3.2-1B-Instruct-Medical-Finetuned-merged) |
328
+ | **Med-LLaMA3.2-3B** | **Adapter** | **this repo** — [`MohamedAhmedAE/Llama-3.2-3B-Instruct-Medical-Finetuned`](https://huggingface.co/MohamedAhmedAE/Llama-3.2-3B-Instruct-Medical-Finetuned) |
329
+ | Med-LLaMA3.2-3B | Merged | [`MohamedAhmedAE/Llama-3.2-3B-Instruct-Medical-Finetuned-merged`](https://huggingface.co/MohamedAhmedAE/Llama-3.2-3B-Instruct-Medical-Finetuned-merged) |
330
+ | Med-LLaMA3.1-8B | Adapter | [`MohamedAhmedAE/Llama-3.1-8B-Instruct-Medical-Finetuned`](https://huggingface.co/MohamedAhmedAE/Llama-3.1-8B-Instruct-Medical-Finetuned) |
331
+ | Med-LLaMA3.1-8B | Merged | [`MohamedAhmedAE/Llama-3.1-8B-Instruct-Medical-Finetuned-merged`](https://huggingface.co/MohamedAhmedAE/Llama-3.1-8B-Instruct-Medical-Finetuned-merged) |
332
+
333
+ **Fine-tuning dataset:** [`MohamedAhmedAE/Med_LLaMa3_fine-tuning_dataset`](https://huggingface.co/datasets/MohamedAhmedAE/Med_LLaMa3_fine-tuning_dataset)