Sudhanshu ShuklaAI Lab · GenAI Engineering
Menu

FROM FIRST PRINCIPLES / 2026

A healthcare LLM,
built from scratch.

An end-to-end PyTorch implementation of MedSparse Healthcare, a Mixtral-inspired sparse Mixture-of-Experts language model — from healthcare-specific tokenization and biomedical pretraining to full-parameter supervised medical fine-tuning.

Explore the design, trace how model weights move between training stages, inspect editable architecture diagrams, and access two distinct releases on Hugging Face.

NEXT RELEASE · full MIRIAD fine-tune, after final testing
Native PyTorch implementation • Healthcare-only pretraining inputs • Fully trainable model
38.8M

Model parameters
Reference trained configuration

04 / 02

Available experts / top-k
Sparse routing per token

5,000

Pretraining step target
Healthcare-domain corpus

2,000

Medical SFT step target
Full-parameter updates

01 / ENGINEERING OVERVIEW

Built to understand every layer.

Rather than loading official pretrained Mixtral weights, the project implements its own Mixtral-inspired decoder and trains it through two explicitly separated stages.

◈01 / ATTENTION

Grouped-query attention

Six query heads and two key/value heads, rotary position embeddings and causal scaled dot-product attention.

GQARoPESDPA
✳02 / MIXTURE-OF-EXPERTS

Top-2 sparse routing

Per-token routing across four independent SwiGLU experts with normalized weights and a balancing objective.

4 expertsTop-2Router loss
∑03 / MODEL TRAINING

Full-model optimization

AdamW updates embeddings, attention, expert weights, router and output head. No LoRA or frozen backbone.

AdamWRMSNormFull SFT
⌘04 / DATA PIPELINE

Healthcare-first datasets

Biomedical text for pretraining, followed by separate medical instruction data and completion-only supervision.

HF DatasetsBPEAnswer masks

02 / END-TO-END LIFECYCLE

One architecture. Two training stages.

The pretrained checkpoint becomes the starting point for medical supervised fine-tuning. The two model releases are separate artifacts with separate documentation.

00DATA & TOKENIZER

Audit, tokenize, pack

Screen approved healthcare corpora, train a biomedical BPE tokenizer, and form causal language-model training sequences.

InputBiomedical text
OutputTokenizer + token IDs
01FROM-SCRATCH PRETRAINING

Train from random weights

Optimize the native MoE Transformer with next-token cross-entropy and an auxiliary expert-load balancing term.

ObjectiveCausal language modeling
ArtifactStage 1 checkpoint
02FULL-PARAMETER MEDICAL SFT

Specialize on medical QA

Initialize from Stage 1 weights, start a fresh optimizer, and supervise only assistant answers and end-of-sequence targets.

ObjectiveCompletion-only loss
ArtifactStage 2 checkpoint

03 / MODEL RELEASES

Explore both Hugging Face models.

Two checkpoints from the same custom architecture: the foundation model after healthcare pretraining and its medical instruction-tuned continuation.

RELEASE / 01 PRETRAINED

Healthcare Pretrained
From Scratch

Randomly initialized PyTorch sparse-MoE language model pretrained on biomedical text. This is the Stage 1 checkpoint, before medical instruction tuning.

Next-token LMMoEPyTorch
RELEASE / 02 FULL SFT

Healthcare Medical
Supervised Fine-Tuning

Stage 1 model weights adapted with full-parameter medical SFT on instruction/response examples. Prompt tokens are excluded from the supervised completion loss.

Medical QAFull weightsCompletion loss
RELEASE / 03 · NEXT

Wednesday, 25 November 2026. A new MedSparse Healthcare checkpoint, fully fine-tuned on the 5.8M-pair MIRIAD medical Q&A dataset, will be published on Hugging Face after final testing on held-out questions. The two releases above stay available.

Both releases use a custom native PyTorch model loader, not necessarily the standard Hugging Face AutoModelForCausalLM API. Model availability depends on repository visibility. These research artifacts are not validated for clinical diagnosis or treatment.

Try both models in your browser.

Both checkpoints run locally with plain JavaScript after a one-time 155 MB download per model. Nothing you type is sent to a server.

Open the playground in a full page ↗

Run the playground on your computer

With Python 3.10 or later, run these commands in your terminal.

python -m pip install medsparse-playground
medsparse-playground

The launcher opens the playground in your browser. The first model download requires internet access. View package on PyPI

04 / MODEL EVALUATION

Held-out results, measured in the browser.

Both checkpoints scored on data they never trained on, picked with the same hash-based splits the training code uses, and run on the same JavaScript engine as the playground above. Evaluated 2026-11-20.

Medical Q&A perplexity253 after SFT

692 before SFT · 64% lower. 80 held-out medical-o1 answers.

PubMed perplexity572 pretrained

667 after SFT. 40 held-out PubMed Central articles.

MedMCQA accuracy29% SFT

33% pretrained · 25% chance · 38% for always answering “A” in this sample. Close to guessing at this size.

Speed in the browser14 tokens/s

Plain JavaScript on one CPU thread, no GPU or server. Measured in a background tab on an 8-thread CPU; about 20 tokens/s in a visible tab.

Lower perplexity is better. Brackets show 95% bootstrap confidence intervals over evaluation items.
MetricPretrainedMedical SFTReference
PubMed held-out perplexity572473–704667546–823Uniform guess: 30,001 · 5,120 tokens
Medical Q&A held-out perplexity692643–741253233–273Answer tokens only · 7,943 tokens
Next-token top-1 accuracy, PubMed15.6%14.3%Exact next-token match
Next-token top-1 accuracy, Q&A14.4%21.6%Exact next-token match
MedMCQA accuracy (150 questions)32.7%25.7%–40.5%28.7%22.0%–36.4%Chance 25% · most common answer 38.0%
Decode speed (browser, CPU)13.7 tokens/s14.0 tokens/s64 greedy tokens, one Web Worker

Training progress

Held-out loss at each published checkpoint, from an untrained model (step 0) through 5,000 pretraining steps and 2,000 medical SFT steps. Dots are measurements with their 95% intervals; dashed lines only connect them.

PubMed held-out (40 articles)Medical Q&A held-out (80 answers)
Held-out loss at each training stage Cross-entropy on held-out data. Untrained guess 10.31 at step 0; after 5,000 pretraining steps PubMed 6.35 and Q&A 6.54; after 2,000 more SFT steps PubMed 6.50 and Q&A 5.53. PRETRAINING SFT 5 6 7 8 9 10 11 Loss (nats/token), lower is better 0 1k 2k 3k 4k 5k 6k 7k Optimizer steps PubMed held-out · untrained (uniform guess over 30,001 tokens): loss 10.31 nats/token (perplexity 30,001) PubMed held-out · after 5,000 pretraining steps: loss 6.35 nats/token (perplexity 572; 95% interval 473–704) PubMed held-out · after 2,000 SFT steps: loss 6.50 nats/token (perplexity 667; 95% interval 546–823) Medical Q&A held-out · untrained (uniform guess over 30,001 tokens): loss 10.31 nats/token (perplexity 30,001) Medical Q&A held-out · after 5,000 pretraining steps: loss 6.54 nats/token (perplexity 692; 95% interval 643–741) Medical Q&A held-out · after 2,000 SFT steps: loss 5.53 nats/token (perplexity 253; 95% interval 233–273) PubMed 6.50 Q&A 5.53 Untrained: 10.31
CheckpointStepPubMed lossQ&A loss
Untrained010.31uniform guess10.31uniform guess
Pretrained5,0006.35perplexity 5726.54perplexity 692
Medical SFT7,0006.50perplexity 6675.53perplexity 253

Stage 1 processed 2.56 million tokens (5,000 steps × 512 tokens, per its training manifest). Pretraining cut PubMed loss from 10.31 to 6.35 nats per token. SFT then lowered Q&A loss from 6.54 to 5.53 while PubMed loss rose to 6.50: the model specialised in the Q&A format.

Per-step loss was printed to the console during these two runs and not saved (the run folders keep only the final checkpoint and a manifest), so there is no step-by-step curve to show yet. The training scripts now write every logged step to metrics.jsonl; the next run will publish its full curve here.

Tiny GPT training log

The AI Lab's other from-scratch model, a 1.06M-parameter GPT-2-style model trained on TinyStories, shown in its own frame. Open the full page ↗

Expert routing

Share of top-2 router selections per expert on the held-out text (Medical SFT). The last column is normalized entropy: 1.00 means perfectly even use of all four experts. Lowest layer: 0.98.

E1E2E3E4H
L1231731290.98
L2222427271.00
L3272422271.00
L4222427261.00

Sample answers (greedy decoding)

Unedited greedy outputs on held-out questions. Greedy decoding exposes what each stage learned most strongly: the pretrained model loops on the author-declaration boilerplate common in PubMed Central articles, and the SFT model loops on medical-o1's most frequent opening. The playground samples with a repetition penalty instead.

Held-out question 1: A 70 year old male patient presented to the emergency depament with pain in epigastrium and difficulty in breathing for 6 hours. On examination, his hea rate was chest examination was normal. The patient has been taking omeprazole for gastresophageal reflux disease for last 6 months. What should be the intial investigation : A. An ECG B. An upper GI endoscopy C. Urgent ultrasound of the abdomen D. An x-ray chest

Medical SFT

The most likely diagnosis for the patient's symptoms, the most likely diagnosis is a most likely diagnosis. This is a most likely to be the most likely diagnosis, which is a most likely diagnosis. This is a most likely diagnosis for the patient's condition, which is a most likely diagnosis.

Pretrained

The authors declare that the study of the manuscript. The authors declare that the study of the manuscript. The authors declare that the study of the study, and is a role of the manuscript. The study was performed by the same-based and the study of the manuscript. The authors

Held-out question 2: In a patient with mitral stenosis and elevated liver enzymes undergoing surgery, which inhalational anesthetic agent should be preferred to minimize the risk of further liver damage?

Medical SFT

The most likely diagnosis for the patient's symptoms, the most likely diagnosis is a most likely diagnosis. This is a most likely diagnosis for the patient's symptoms, which is a most likely role in the patient's symptoms. This is a most likely diagnosis for the patient's symptoms, which is a most

Pretrained

The authors declare that the study of the study. The authors declare that the study of the study, the study is a role of the manuscript. The study was performed by the study. The authors declare that the study of the study, the study is a role of the manuscript.

How this was measured, and the limits
  • What it means. Medical SFT lowers held-out Q&A perplexity by 64% (692 → 253; paired 95% CI of the ratio 0.34–0.39). On PubMed text the pretrained checkpoint stays better (572 vs 667): SFT trades some general biomedical fit for the Q&A format. On MedMCQA the SFT model is not distinguishable from chance and the pretrained model is slightly above chance, but below always answering the most common letter (38%): expected for 38.8M parameters. The clearest improvement to make next: only 9% of held-out Q&A examples keep the whole question inside the 128-token training window, so SFT mostly learns answer style without the question. Fine-tuning with longer sequences (for example 512 tokens) should help most.
  • Held-out data. PubMed: the first 40 articles in licensed_pubmed-0000.json.gz that pass the training filters (clinical keywords, CC0/CC-BY licence) and fall in the 2% validation partition of stable_partition (2,407 scanned). Q&A: the first 80 medical-o1 (en) rows in the 5% validation bucket of bucket_for_question. Both splits use BLAKE2b with seed 42, re-implemented in JavaScript and checked against Python's hashlib.
  • Scoring. PubMed uses the packed pretraining window (128 scored tokens per article, no <bos>). Q&A mirrors tokenize_example(seq_len=128): the chat template, answer-only loss, and the prompt trimmed from the left. Because answers are long, only 9% of these examples keep the whole question inside the 128-token window, which is also true of training.
  • MedMCQA. The first 150 validation questions; each option is scored by its mean log-probability per token after the question (cloze style, options not shown). Wilson 95% intervals.
  • Engine. The playground's float32 JavaScript implementation of the published weights (Hugging Face revisions bb8e91ae and 0a157beb), not PyTorch. Uncertainty: 2,000-sample bootstrap over items.
  • Not a clinical evaluation. These numbers measure language modelling on held-out text. They say nothing about medical safety or correctness.

05 / ARCHITECTURE & DESIGN

Architecture you can inspect.

Switch between high-level architecture, decoder internals, and the checkpoint lifecycle. Diagrams use editable Mermaid.js source.

High-Level Architecture

Datasets, tokenization, random-initialized pretraining, full medical SFT and validation.

Loading architecture diagram…

View the editable Mermaid.js source
Select a diagram to load its source.

Mermaid.js diagrams load when connected to the internet. Direct source files remain available.

06 / DOCUMENTATION DIRECTORY

From visual design to source code.

Use the implementation, README, GitHub Wiki and editable diagrams to follow or reproduce the training workflow.

OPEN ENGINEERING / REPRODUCIBLE DESIGN

Read the code.
Trace the weights.

Learn how a native sparse Mixture-of-Experts language model progresses from randomly initialized parameters to biomedical pretraining and full medical SFT.

Get in touch

Questions about this project?

Ask about the code, a collaboration or an AI engineering role. Messages go straight to my inbox, and I'll reply by email.

More work: Sudhanshu Shukla's AI Lab ↗

Form not loading? Open the contact page ↗