File size: 9,331 Bytes
2c4e2b9
6db5d25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c4e2b9
 
6db5d25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c4e2b9
6db5d25
 
 
2c4e2b9
6db5d25
 
 
 
 
 
 
 
 
2c4e2b9
6db5d25
2c4e2b9
6db5d25
2c4e2b9
6db5d25
2c4e2b9
6db5d25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
---
license: gemma
base_model: unsloth/gemma-3n-E4B-it
tags:
- medical
- emergency
- first-aid
- healthcare
- offline
- gemma3n
- unsloth
- medical-ai
language:
- en
datasets:
- ericrisco/medrescue
pipeline_tag: text-generation
---

# Medical Gemma-3N: Emergency Medical Assistant πŸ₯

**Medical Gemma-3N** is a specialized version of Google's Gemma-3N-4B model, fine-tuned specifically for **emergency medical assistance** and **offline healthcare applications**. This model is designed to provide accurate medical guidance in emergency scenarios where internet connectivity may be limited or unavailable.

## 🎯 Model Overview

- **Base Model**: [unsloth/gemma-3n-E4B-it](https://huggingface.co/unsloth/gemma-3n-E4B-it)
- **Training Dataset**: [ericrisco/medrescue](https://huggingface.co/datasets/ericrisco/medrescue) (86,667 medical Q&A pairs)
- **Training Method**: LoRA (Low-Rank Adaptation) fine-tuning
- **Optimization**: Unsloth framework for 2x faster training
- **Model Size**: 7.8B parameters + 76.9MB LoRA adapters
- **Training Loss**: 0.002 (excellent convergence)

## πŸš€ Key Features

- **πŸ₯ Medical Expertise**: Trained on 80K+ medical Q&A pairs from authoritative sources
- **🚨 Emergency Focus**: Specialized in first aid, emergency care, and rescue procedures  
- **πŸ“± Offline Capable**: Optimized for deployment without internet connectivity
- **⚑ Edge Optimized**: Efficient inference on local devices and mobile platforms
- **🎯 Clinical Accuracy**: 72% accuracy on medical benchmarks (vs 36% baseline)
- **πŸ”’ Privacy First**: No data leaves your device during inference

## πŸ“Š Performance Benchmarks

| Metric | Base Gemma-3N | Medical Gemma-3N | Improvement |
|--------|---------------|------------------|-------------|
| **First Aid Accuracy** | 36.15% | 71.54% | **+35.39%** |
| **Medical Terminology** | Limited | Comprehensive | Clinical-grade |
| **Emergency Response** | Generic | Specialized | Professional |
| **Offline Performance** | Standard | Optimized | Edge-ready |

*Evaluated on [lextale/FirstAidInstructionsDataset](https://huggingface.co/datasets/lextale/FirstAidInstructionsDataset)*

## πŸ’» Quick Start

### Installation

```bash
pip install torch transformers accelerate
```

### Basic Usage

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

# Load model and tokenizer
model_name = "ericrisco/medical-gemma-3n-4b"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype=torch.float16,
    device_map="auto"
)

# Medical consultation example
def ask_medical_question(question):
    prompt = f"<start_of_turn>user\n{question}<end_of_turn>\n<start_of_turn>model\n"
    
    inputs = tokenizer.encode(prompt, return_tensors="pt")
    
    with torch.no_grad():
        outputs = model.generate(
            inputs,
            max_new_tokens=512,
            temperature=0.7,
            do_sample=True,
            pad_token_id=tokenizer.eos_token_id
        )
    
    response = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return response.split("<start_of_turn>model\n")[-1]

# Example usage
question = "What should I do if someone is having a heart attack?"
response = ask_medical_question(question)
print(response)
```

### Advanced Usage with Streaming

```python
from transformers import TextIteratorStreamer
from threading import Thread

def stream_medical_response(question):
    prompt = f"<start_of_turn>user\n{question}<end_of_turn>\n<start_of_turn>model\n"
    inputs = tokenizer.encode(prompt, return_tensors="pt")
    
    streamer = TextIteratorStreamer(tokenizer, skip_special_tokens=True)
    
    generation_kwargs = dict(
        inputs=inputs,
        streamer=streamer,
        max_new_tokens=512,
        temperature=0.7,
        do_sample=True,
        pad_token_id=tokenizer.eos_token_id
    )
    
    thread = Thread(target=model.generate, kwargs=generation_kwargs)
    thread.start()
    
    generated_text = ""
    for new_text in streamer:
        generated_text += new_text
        print(new_text, end="", flush=True)
    
    return generated_text

# Stream response
question = "How do I treat severe bleeding?"
stream_medical_response(question)
```

## 🎯 Use Cases

### 🚨 Emergency Scenarios
- **First Aid Guidance**: Step-by-step emergency procedures
- **Symptom Assessment**: Initial triage and severity evaluation  
- **Drug Information**: Medication guidance and contraindications
- **Disaster Response**: Medical care in resource-limited settings

### πŸ₯ Healthcare Applications  
- **Medical Education**: Training support for healthcare students
- **Rural Healthcare**: Medical assistance in underserved areas
- **Telemedicine**: Offline medical consultation capabilities
- **Clinical Decision Support**: Evidence-based medical recommendations

### πŸ“± Mobile & Edge Deployment
- **Emergency Apps**: Offline medical guidance applications
- **Wearable Devices**: Health monitoring and emergency response  
- **Remote Areas**: Medical assistance without connectivity
- **Privacy-Focused**: Local processing without data transmission

## πŸ“š Training Dataset

The model was trained on **[ericrisco/medrescue](https://huggingface.co/datasets/ericrisco/medrescue)**, a comprehensive medical dataset containing:

- **86,667 medical Q&A pairs** from multiple authoritative sources
- **11 specialized medical datasets** covering clinical reasoning, symptoms, medications
- **14 official medical PDFs** from WHO, ICRC, military, and government sources  
- **RAG-enhanced content** using vector search and AI generation
- **Quality validation** with strict medical accuracy filtering

### Dataset Sources Include:
- Medical licensing exam questions with detailed explanations
- Clinical reasoning chains for diagnostic procedures  
- Emergency medicine protocols and first aid instructions
- Medication information and drug interaction guidance
- Symptom analysis and differential diagnosis training
- Disaster response and rescue operation procedures

## βš™οΈ Technical Details

### Training Configuration
- **Base Model**: Gemma-3N-E4B-it (7.8B parameters)
- **Fine-tuning Method**: LoRA (r=8, alpha=8, dropout=0)
- **Training Framework**: Unsloth (2x speed optimization)
- **Quantization**: 4-bit loading for memory efficiency
- **Sequence Length**: 1024 tokens
- **Batch Size**: 16 effective (4Γ—4 gradient accumulation)
- **Learning Rate**: 2e-5 with linear scheduling
- **Training Time**: ~4.5 hours on Tesla T4

### Model Architecture
- **Parameters Trained**: 19.2M out of 7.8B (0.24% efficient adaptation)
- **Target Modules**: Attention and MLP layers
- **Optimization**: AdamW 8-bit with gradient checkpointing
- **Memory Usage**: Fits on 16GB GPU with 4-bit quantization
- **Inference Speed**: 317 samples/second during training

## πŸ”„ Model Variants

This model is available in multiple formats for different deployment scenarios:

1. **[ericrisco/medical-gemma-3n-lora](https://huggingface.co/ericrisco/medical-gemma-3n-lora)** - LoRA adapters (76.9MB)
2. **[ericrisco/medical-gemma-3n-lora-gguf](https://huggingface.co/ericrisco/medical-gemma-3n-lora-gguf)** - GGUF quantized for llama.cpp
3. **ericrisco/medical-gemma-3n-4b** - Full merged model (this repository)

## πŸ“‹ Evaluation Results

Evaluated on [lextale/FirstAidInstructionsDataset](https://huggingface.co/datasets/lextale/FirstAidInstructionsDataset) using AI judge scoring:

```
Base Gemma-3N:     36.15% accuracy (47/130)
Medical Gemma-3N:  71.54% accuracy (93/130)
Improvement:       +35.39% absolute gain
```

The model shows significant improvement in:
- **Medical terminology** understanding and usage
- **Clinical reasoning** and diagnostic procedures  
- **Emergency response** protocols and first aid
- **Drug information** and medication guidance
- **Safety considerations** in medical recommendations

## ⚠️ Important Disclaimers

- **🚨 Not a substitute for professional medical advice**
- **πŸ₯ Always consult healthcare professionals for medical decisions**  
- **πŸ“ž Call emergency services (911/112) for life-threatening situations**
- **πŸ”¬ For research and educational purposes only**
- **βš–οΈ Users assume full responsibility for model usage**

## πŸ› οΈ Hardware Requirements

### Minimum Requirements
- **GPU**: 8GB VRAM (with 4-bit quantization)
- **RAM**: 16GB system memory
- **Storage**: 20GB for model and dependencies

### Recommended Requirements  
- **GPU**: 16GB+ VRAM (RTX 4080/A100)
- **RAM**: 32GB+ system memory
- **Storage**: 50GB+ SSD for optimal performance

## πŸ“– Citation

If you use this model in your research or applications, please cite:

```bibtex
@misc{medical_gemma_3n,
  title={Medical Gemma-3N: Emergency Medical Assistant for Offline Healthcare},
  author={Eric Risco},
  year={2025},
  url={https://huggingface.co/ericrisco/medical-gemma-3n-4b},
  note={Fine-tuned on 86,667 medical Q&A pairs for emergency assistance}
}
```

## 🀝 Contributing

This model is part of the [Gemma3N Impact Challenge](https://github.com/ericrisco/gemma3n-impact-challenge) project. Contributions, feedback, and improvements are welcome!

## πŸ“œ License

This model is released under the Gemma License. Please review the license terms before use in commercial applications.