Files changed (1) hide show
  1. README.md +276 -56
README.md CHANGED
@@ -12,87 +12,307 @@ tags:
12
  - pharma
13
  - medical
14
  - domain-specific
 
 
 
 
15
  pipeline_tag: text-generation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  ---
17
 
18
  # PharmaGPT-336M
19
 
20
- A **336M parameter GPT** language model trained **entirely from scratch** on 200K synthetic pharmaceutical documents across 6 domains.
21
 
22
- No pre-trained weights, no fine-tuning β€” every component built from scratch: custom BPE tokenizer, full transformer architecture, training loop.
23
 
24
- ## Model Details
 
 
25
 
26
- | Property | Value |
27
- |---|---|
28
- | Parameters | 336,380,928 (336.4M) |
29
- | Architecture | Decoder-only Transformer (GPT) |
30
- | Embedding Dim | 1024 |
31
- | Attention Heads | 16 |
32
- | Layers | 24 |
33
- | Context Length | 1024 |
34
- | Vocabulary | 32,000 tokens (custom BPE) |
35
- | Positional Encoding | Rotary (RoPE) |
36
- | Normalization | RMSNorm |
37
- | Activation | SwiGLU |
38
- | Val Loss | 0.4985 |
39
- | Perplexity | 1.65 |
40
-
41
- ## Pharma Domains Covered
42
-
43
- 1. **Manufacturing Deviation Reports** β€” equipment failures, process excursions, root cause analysis, CAPA
44
- 2. **Batch Production Records** β€” raw materials, process steps, yield, disposition
45
- 3. **SOP Q&A** β€” cleaning validation, environmental monitoring, aseptic processing, water systems
46
- 4. **Stability Studies** β€” ICH Q1A conditions, assay trending, shelf life prediction
47
- 5. **Pharmacovigilance (ICSR)** β€” adverse event narratives, WHO-UMC causality assessment
48
- 6. **Scientific Writing** β€” formulation development, DoE, analytical methods, results sections
49
-
50
- ## Architecture
51
-
52
- Uses modern architectural choices from Llama / Mistral:
53
- - **RoPE** (Rotary Positional Embeddings) β€” encodes relative position
54
- - **RMSNorm** β€” faster, simpler alternative to LayerNorm
55
- - **SwiGLU** β€” gated activation function
56
- - **No bias** in linear layers
57
- - **Weight tying** between token embedding and output projection
58
-
59
- ## Training
60
-
61
- - **Data**: 200K synthetic pharmaceutical samples (~32M tokens) generated with domain-specific templates
62
- - **Tokenizer**: Custom BPE (32K vocab) trained on the pharma corpus
63
- - **Optimizer**: AdamW (b1=0.9, b2=0.95, weight decay=0.1)
64
- - **Schedule**: Cosine LR decay with 500-step linear warmup
65
- - **Hardware**: Kaggle T4 GPU, 15K iterations across multiple sessions
66
- - **Precision**: float16 mixed precision with gradient checkpointing
67
-
68
- ## Usage
69
 
70
  ```python
71
  import torch
72
  from tokenizers import Tokenizer
73
- from model import GPT, GPTConfig
74
 
 
75
  ckpt = torch.load("best_model.pt", map_location="cpu", weights_only=False)
 
 
 
76
  model = GPT(ckpt["model_config"])
77
  model.load_state_dict(ckpt["model"])
78
  model.eval()
79
 
 
80
  tok = Tokenizer.from_file("tokenizer/tokenizer.json")
81
 
 
82
  prompt = "<|deviation|>\nDuring manufacturing of Batch B-NDL-2026"
83
  ids = torch.tensor([tok.encode(prompt).ids])
84
- out = model.generate(ids, max_new_tokens=200, temperature=0.8, top_k=50)
85
- print(tok.decode(out[0].tolist()))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  ```
87
 
88
- ## Limitations
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
- - Trained on **synthetic** data only β€” does not contain real pharmaceutical knowledge
91
- - Not suitable for clinical or regulatory decision-making
92
- - 336M parameters β€” small model, not comparable to large LLMs
93
- - May generate plausible-sounding but factually incorrect pharmaceutical content
94
- - English only
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
  ## License
97
 
98
- Apache 2.0
 
12
  - pharma
13
  - medical
14
  - domain-specific
15
+ - rope
16
+ - rmsnorm
17
+ - swiglu
18
+ - synthetic-data
19
  pipeline_tag: text-generation
20
+ model-index:
21
+ - name: PharmaGPT-336M
22
+ results:
23
+ - task:
24
+ type: text-generation
25
+ name: Text Generation
26
+ metrics:
27
+ - name: Validation Loss
28
+ type: loss
29
+ value: 0.3748
30
+ - name: Perplexity
31
+ type: perplexity
32
+ value: 1.45
33
+ - name: Training Loss
34
+ type: loss
35
+ value: 0.3748
36
  ---
37
 
38
  # PharmaGPT-336M
39
 
40
+ A **336M parameter GPT** language model trained **entirely from scratch** on 200K synthetic pharmaceutical documents across 6 manufacturing domains.
41
 
42
+ **No pre-trained weights. No fine-tuning. Every component built from scratch**: custom BPE tokenizer, full transformer architecture (RoPE + RMSNorm + SwiGLU), training loop, and evaluation pipeline.
43
 
44
+ > **Paper**: [ArXiv preprint (coming soon)]()
45
+ > **Blog**: [Medium article (coming soon)]()
46
+ > **Code**: Included in this repository
47
 
48
+ ---
49
+
50
+ ## Quick Start
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  ```python
53
  import torch
54
  from tokenizers import Tokenizer
 
55
 
56
+ # Download model files from this repo, then:
57
  ckpt = torch.load("best_model.pt", map_location="cpu", weights_only=False)
58
+
59
+ # Reconstruct model from saved config
60
+ from model import GPT # model.py included in this repo
61
  model = GPT(ckpt["model_config"])
62
  model.load_state_dict(ckpt["model"])
63
  model.eval()
64
 
65
+ # Load tokenizer
66
  tok = Tokenizer.from_file("tokenizer/tokenizer.json")
67
 
68
+ # Generate pharmaceutical text
69
  prompt = "<|deviation|>\nDuring manufacturing of Batch B-NDL-2026"
70
  ids = torch.tensor([tok.encode(prompt).ids])
71
+ output = model.generate(ids, max_new_tokens=200, temperature=0.8, top_k=50)
72
+ print(tok.decode(output[0].tolist()))
73
+ ```
74
+
75
+ ### Generation with Different Domains
76
+
77
+ ```python
78
+ prompts = {
79
+ "deviation": "<|deviation|>\nDuring routine inspection of the tablet coating line",
80
+ "batch_record": "<|batch_record|>\nBATCH PRODUCTION RECORD\nProduct: Metformin HCl 500mg Tablets",
81
+ "sop": "<|sop|>\nSOP-ENV-205 | Environmental Monitoring Program",
82
+ "stability": "<|stability_study|>\nSTABILITY STUDY REPORT\nProduct: Adalimumab 40mg/0.8mL",
83
+ "pharmacovigilance": "<|icsr|>\nA 72-year-old female patient with history of diabetes",
84
+ "scientific": "<|scientific_paper|>\nObjective: To evaluate the impact of granulation",
85
+ }
86
+
87
+ for domain, prompt in prompts.items():
88
+ ids = torch.tensor([tok.encode(prompt).ids])
89
+ out = model.generate(ids, max_new_tokens=150, temperature=0.8, top_k=50)
90
+ print(f"\n{'='*60}\n[{domain.upper()}]\n{'='*60}")
91
+ print(tok.decode(out[0].tolist()))
92
+ ```
93
+
94
+ ---
95
+
96
+ ## Model Details
97
+
98
+ | Property | Value |
99
+ |---|---|
100
+ | **Parameters** | 336,380,928 (336M) |
101
+ | **Architecture** | Decoder-only Transformer (GPT) |
102
+ | **Embedding Dimension** | 1024 |
103
+ | **Attention Heads** | 16 |
104
+ | **Layers** | 24 |
105
+ | **Context Length** | 512 tokens |
106
+ | **Vocabulary** | 32,000 tokens (custom BPE) |
107
+ | **Positional Encoding** | Rotary (RoPE), base=10000 |
108
+ | **Normalization** | RMSNorm (Ξ΅=1e-6) |
109
+ | **Activation** | SwiGLU (FFN hidden=2752) |
110
+ | **Bias** | None (all linear layers) |
111
+ | **Weight Tying** | Embedding ↔ LM Head |
112
+ | **Dropout** | 0.1 |
113
+
114
+ ### Architecture Highlights
115
+
116
+ This model implements the same architectural innovations found in LLaMA/Mistral, all coded from scratch:
117
+
118
+ - **RoPE** (Rotary Positional Embeddings) β€” encodes relative position through rotation of Q/K vectors
119
+ - **RMSNorm** β€” faster, simpler alternative to LayerNorm (no mean subtraction)
120
+ - **SwiGLU** β€” gated feed-forward network with Swish activation
121
+ - **No bias** in any linear layer β€” modern simplification
122
+ - **Weight tying** β€” token embedding and output projection share parameters
123
+ - **Pre-norm** architecture β€” normalize before attention/FFN, not after
124
+
125
+ ---
126
+
127
+ ## Training Details
128
+
129
+ | Parameter | Value |
130
+ |---|---|
131
+ | **Optimizer** | AdamW (β₁=0.9, Ξ²β‚‚=0.95, wd=0.1) |
132
+ | **Learning Rate** | 2e-4 (peak), cosine decay |
133
+ | **Warmup** | 500 steps (linear) |
134
+ | **Batch Size** | 8 micro Γ— 4 grad accum = 32 effective |
135
+ | **Iterations** | 15,000 |
136
+ | **Precision** | float16 mixed precision |
137
+ | **Gradient Clipping** | 1.0 (global norm) |
138
+ | **Gradient Checkpointing** | Enabled |
139
+ | **Hardware** | NVIDIA T4 (16GB), Kaggle free tier |
140
+ | **Training Time** | ~9 hours |
141
+ | **Cost** | $0 (free compute) |
142
+
143
+ ### Training Results
144
+
145
+ | Metric | Value |
146
+ |---|---|
147
+ | Final Training Loss | 0.3748 |
148
+ | Best Validation Loss | 0.3748 |
149
+ | Validation Perplexity | 1.45 |
150
+ | Tokens Processed | ~245M |
151
+
152
+ *Note: Low perplexity reflects the structured/templated nature of synthetic training data. Real-world pharmaceutical text would yield higher perplexity.*
153
+
154
+ ---
155
+
156
+ ## Training Data: 6 Pharmaceutical Domains
157
+
158
+ The model was trained on 200K synthetic documents (~32M tokens) generated across six pharmaceutical manufacturing domains:
159
+
160
+ ### 1. Manufacturing Deviation Reports (~33K samples)
161
+ Equipment failures, process excursions, out-of-specification results, root cause analysis (Ishikawa, 5-Why), CAPA documentation following ICH Q10.
162
+
163
+ ### 2. Batch Production Records (~33K samples)
164
+ Raw material dispensing, process step documentation, in-process controls, critical process parameters (CPPs), yield calculations, lot disposition decisions.
165
+
166
+ ### 3. Standard Operating Procedures (~33K samples)
167
+ Cleaning validation, environmental monitoring, aseptic processing, water system maintenance (WFI, PW), equipment qualification β€” in Q&A format.
168
+
169
+ ### 4. Stability Studies (~33K samples)
170
+ ICH Q1A(R2) study designs, accelerated (40Β°C/75% RH) and long-term (25Β°C/60% RH) conditions, assay trending, degradation products, shelf-life determination.
171
+
172
+ ### 5. Pharmacovigilance Case Reports (~33K samples)
173
+ Individual Case Safety Reports (ICSRs), adverse event narratives, MedDRA coding, WHO-UMC causality assessment (certain/probable/possible/unlikely).
174
+
175
+ ### 6. Scientific Writing (~33K samples)
176
+ Formulation development, Design of Experiments (DoE), analytical method development/validation, dissolution studies, results and discussion sections.
177
+
178
+ ---
179
+
180
+ ## Special Tokens
181
+
182
+ | Token | Purpose | Example Use |
183
+ |---|---|---|
184
+ | `<\|deviation\|>` | Start of deviation report | Triggers investigation-style generation |
185
+ | `<\|batch_record\|>` | Start of batch record | Triggers manufacturing record format |
186
+ | `<\|sop\|>` | Start of SOP document | Triggers procedural/Q&A format |
187
+ | `<\|stability_study\|>` | Start of stability study | Triggers ICH-compliant study format |
188
+ | `<\|icsr\|>` | Start of pharmacovigilance case | Triggers adverse event narrative |
189
+ | `<\|scientific_paper\|>` | Start of scientific writing | Triggers academic/research style |
190
+ | `<\|end\|>` | End of document | Marks document boundary |
191
+
192
+ ---
193
+
194
+ ## Repository Contents
195
+
196
+ ```
197
+ β”œβ”€β”€ best_model.pt # Full checkpoint (model weights + config + metadata)
198
+ β”œβ”€β”€ config.json # Architecture specification (JSON)
199
+ β”œβ”€β”€ tokenizer/
200
+ β”‚ └── tokenizer.json # Trained BPE tokenizer (32K vocab)
201
+ β”œβ”€β”€ model.py # Complete model source code (GPT + all components)
202
+ β”œβ”€β”€ tokenizer.py # Tokenizer training/loading utilities
203
+ └── README.md # This file
204
  ```
205
 
206
+ ### Loading Without `model.py`
207
+
208
+ If you want to inspect the architecture without running the custom code:
209
+
210
+ ```python
211
+ import torch, json
212
+
213
+ # Load config
214
+ with open("config.json") as f:
215
+ config = json.load(f)
216
+ print(config)
217
+ # {'vocab_size': 32000, 'n_embd': 1024, 'n_head': 16, 'n_layer': 24, ...}
218
+
219
+ # Load checkpoint metadata
220
+ ckpt = torch.load("best_model.pt", map_location="cpu", weights_only=False)
221
+ print(f"Keys: {ckpt.keys()}")
222
+ print(f"Val loss: {ckpt.get('best_val_loss')}")
223
+ print(f"Iteration: {ckpt.get('iter_num')}")
224
+ ```
225
 
226
+ ---
227
+
228
+ ## Intended Use
229
+
230
+ ### Primary Use Cases
231
+ - **Educational**: Understanding how modern GPT architectures work end-to-end
232
+ - **Research baseline**: Starting point for pharmaceutical NLP research
233
+ - **Template generation**: Generating draft pharmaceutical document structures
234
+ - **Domain adaptation**: Fine-tuning on real pharmaceutical data for production use
235
+
236
+ ### Out-of-Scope Uses
237
+ - **Clinical decision-making**: This model generates plausible but NOT factually verified content
238
+ - **Regulatory submissions**: Generated text requires expert review and verification
239
+ - **Production deployment without validation**: The model was trained on synthetic data only
240
+ - **General-purpose chat**: This is a domain-specific completion model, not a chatbot
241
+
242
+ ---
243
+
244
+ ## Limitations and Risks
245
+
246
+ | Limitation | Impact | Mitigation |
247
+ |---|---|---|
248
+ | Synthetic training data | May generate structurally correct but factually wrong content | Always verify with domain experts |
249
+ | 336M parameters | Limited reasoning and knowledge capacity | Use as starting point, not final solution |
250
+ | English only | Cannot process multilingual pharmaceutical docs | Extend training data for other languages |
251
+ | No instruction tuning | Cannot follow complex instructions | Fine-tune with instruction data |
252
+ | Context length (512) | Cannot process long documents in one pass | Chunk documents or extend context |
253
+
254
+ ### Ethical Considerations
255
+ - Generated pharmaceutical content should NEVER be used for actual drug manufacturing without expert review
256
+ - The model may reproduce biases present in the synthetic data templates
257
+ - Not intended as a replacement for qualified pharmaceutical professionals
258
+
259
+ ---
260
+
261
+ ## Citation
262
+
263
+ If you use PharmaGPT in your research, please cite:
264
+
265
+ ```bibtex
266
+ @misc{chaturvedi2026pharmagpt,
267
+ title={PharmaGPT: A Domain-Specific Language Model for Pharmaceutical Manufacturing Intelligence Trained from Scratch on Synthetic Data},
268
+ author={Chaturvedi, Parth},
269
+ year={2026},
270
+ howpublished={\url{https://huggingface.co/ParthChat1802/PharmaGPT-336M}},
271
+ }
272
+ ```
273
+
274
+ ---
275
+
276
+ ## Technical Notes for Reproducibility
277
+
278
+ ### Checkpoint Format
279
+
280
+ The `best_model.pt` file is a PyTorch checkpoint dictionary containing:
281
+
282
+ ```python
283
+ {
284
+ "model": OrderedDict, # model.state_dict()
285
+ "model_config": GPTConfig, # dataclass with architecture params
286
+ "config": dict, # training configuration
287
+ "iter_num": int, # iteration at save time
288
+ "best_val_loss": float, # best validation loss achieved
289
+ }
290
+ ```
291
+
292
+ ### System Requirements
293
+
294
+ - **Inference**: Any machine with 2GB+ RAM and PyTorch installed
295
+ - **Training (reproduce)**: NVIDIA GPU with 8GB+ VRAM, or Apple M-series with 16GB+ unified memory
296
+ - **Dependencies**: `torch>=2.0`, `tokenizers>=0.13`
297
+
298
+ ### Reproducing Training
299
+
300
+ ```bash
301
+ git clone <source-repo>
302
+ cd gpt-from-scratch
303
+ pip install -r requirements.txt
304
+
305
+ # Generate data
306
+ python -m data.generators.master_generator
307
+
308
+ # Train tokenizer + model
309
+ python -m src.train_pharma
310
+ ```
311
+
312
+ Or use the Kaggle notebook for GPU-accelerated training (see repository).
313
+
314
+ ---
315
 
316
  ## License
317
 
318
+ **Apache 2.0** β€” Use freely for any purpose (commercial, research, educational). Attribution appreciated but not legally required beyond the license notice.