/ Модель

Характеристики

Лицензия
Apache 2.0
Архитектура
medllm · dense
Библиотека
transformers
Опубликована
13 окт 2026

medllm-dpo-medmcqa

Генерация текстаТекст → текст3 профессии
83скачиваний за 30 дней0лайковвеса обновлены13 окт 2026

Описание модели

Составлено на русском по карточке модели и метаданным Hugging Face

Небольшая англоязычная медицинская модель для ранжирования ответов в тестах с множественным выбором, настроенная на MedMCQA.

MedLLM-DPO-MedMCQA — англоязычная медицинская языковая модель Maxx Richard Rahman, Asim Ahmed, Mihan Mohagheghzadeh и Wolfgang Maass из DFKI и Саарского университета. Это декодерный Transformer семейства MedLLM с 100,29 млн параметров, реализованный для Transformers; модель обучена с нуля, затем дообучена на медицинских веб-текстах и настроена с помощью SFT и DPO на наборе MedMCQA.

Модель предназначена прежде всего для ранжирования вариантов ответа в медицинских тестах с множественным выбором. В README приведены результаты на MedMCQA и на девяти медицинских разделах MMLU; оценка выполнялась по логарифмическим вероятностям вариантов. Окно контекста — 512 токенов. Репозиторий содержит веса safetensors и требует загрузки пользовательской архитектуры через Transformers.

Модель рассчитана на исследования небольших специализированных языковых моделей и бенчмаркинг медицинских вопросов. Качество свободной генерации не оценивалось и ожидается низким; модель слаба на клинических виньетках MedQA, а её перенос на другие форматы подтверждён только для MMLU-Medical. Она не предназначена для диагностики, лечебных решений, советов пациентам или клинического применения. Лицензия — Apache-2.0.

Сценарии применения

  • выбор наиболее вероятного варианта ответа в медицинском тесте MedMCQA
  • оценка ответов на вопросы MMLU-Medical
  • бенчмаркинг компактных медицинских языковых моделей
  • исследование влияния SFT и DPO на медицинские тесты

Ограничения

Модель обучалась как ранжировщик вариантов ответа, поэтому качество свободной генерации не оценено и ожидается низким; на клинических виньетках MedQA она показывает результаты около нижнего уровня задачи. Не использовать для диагностики, лечебных решений или советов пациентам; контекст ограничен 512 токенами.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus, LLM Stats

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

MedLLM-DPO — MedMCQA & MMLU-Medical

MedLLM is an open 0.1B-parameter (100.29M) decoder-only medical language model trained from scratch through a fully open three-phase pipeline: general pretraining, domain fine-tuning on the MedFineWeb medical web corpus, and preference-aligned fine-tuning (SFT + DPO). It is described in the paper MedLLM: An Open Medical Language Model at the Sub-Billion Scale (Rahman, Ahmed, Mohagheghzadeh & Maass, 2026).

This checkpoint is the DPO-aligned model for MedMCQA (4-option Indian medical entrance exam questions). It is also the checkpoint used for MMLU-Medical evaluation (cross-domain transfer, no MMLU training data). It starts from the shared domain-fine-tuned MedLLM checkpoint and is then trained with supervised fine-tuning followed by direct preference optimization on the MedMCQA training set.

Key finding of the paper. At sub-billion scale, medical competence does not degrade uniformly under compression but splits by task type. MedLLM is strong on context-grounded QA (PubMedQA) and on MedMCQA, where it exceeds every 7B and sub-7B baseline, while it stays near the task floor on clinical-vignette MedQA. The paper argues that this dissociation is masked at 7B and surfaces only when capacity is scarce.

Model family

RepositoryAligned forScore
maxxrichard/medllm-dpo-medmcqaMedMCQA & MMLU-MedicalMedMCQA 34.9%, MMLU-Medical 32.4%
maxxrichard/medllm-dpo-medqaMedQAMedQA 28.1%
maxxrichard/medllm-dpo-pubmedqaPubMedQAPubMedQA 58.2%

All three share the same pretraining, domain fine-tuning stage, tokenizer and architecture. They differ only in the SFT + DPO data.

Model details

PropertyValue
Developed byMaxx Richard Rahman, Asim Ahmed, Mihan Mohagheghzadeh, Wolfgang Maass (DFKI & Saarland University)
Model typeDecoder-only Transformer (OLMo-2 style), custom transformers implementation
Parameters100.29M
Layers / d_model / heads20 / 512 / 8 (head dim 64)
FFN2048, SwiGLU
NormalizationPre-norm RMSNorm (ε = 1e-6)
Positional encodingRotary (RoPE, base 10,000)
EmbeddingsWeight-tied input / output, vocab 32,000
Context length512 tokens
TokenizerSentencePiece unigram, 32k vocab, trained on general + medical text (tokenizer.model)
Precisionfloat32 weights (model.safetensors, 467 MB)
LanguageEnglish
LicenseApache 2.0
PaperarXiv:2607.27490

Training

Phase 1 — General pretraining

Data≈46.08M documents, ≈29.5B tokens (45 GB): RedPajama-V2 (7.55M docs), C4 (32.0M), OpenWebText (8.01M), Wikipedia (6.41M)
ObjectiveCausal LM with z-loss (weight 1e-4)
Steps200,000
CurriculumSequence length 128 → 256 → 512 in three stages
Final validation loss4.005
Hardware2× NVIDIA H100

Phase 2 — Domain fine-tuning on MedFineWeb

MedFineWeb is a reference-guided medical corpus selected from general web text. General-web documents are split into ≈1,000-word chunks (2M candidates), embedded with a Sentence-Transformer, and scored by mean cosine similarity to their top-5 nearest medical QA references (20,000 MedMCQA, 10,178 MedQA and 20,000 PubMedQA examples, used for selection only, never as training text). The top 50% per reference set is kept, then merged and deduplicated.

Corpus size≈3M chunks, ≈3B SentencePiece tokens (≈1,000 tokens per chunk)
Steps25,000
Learning rate5e-5
Validation perplexity27.3 (step 1k) → 15.68 (step 8k) → 13.62 (step 25k)

Phase 3 — SFT + DPO for MedMCQA (this checkpoint)

Training examples182,822
SFT8,000 steps, batch 32, LR 2e-5, label-prediction loss over all options
DPO2,000 steps, batch 32, LR 5e-6, β = 0.1, reference policy = the SFT model
Preference pairsThe correct answer is paired against each incorrect answer
Hardware2× NVIDIA A100

Evaluation

Protocol. MedLLM is evaluated zero-shot by log-probability ranking (top-token selection): the predicted answer is the option whose answer token receives the highest log-probability. Results are the mean ± standard deviation over three seeds. Pretrained baselines use 3-shot in-context learning; fine-tuned baselines use the same top-token selection. MMLU-Medical covers 1,862 items across nine medical subjects and is scored with the MedMCQA-aligned checkpoint.

This checkpoint

BenchmarkSplitAccuracy (%)
MedMCQAMedMCQA (validation, 4,183 items)34.9 ± 0.6
MMLU-MedicalMMLU-Medical (9 medical subjects, 1,862 items)32.4 ± 1.0

Full comparison (Table 4 of the paper, accuracy %)

ModelParamsMMLU-MedPubMedQAMedMCQAMedQAAvg
Mistral-7B*7B25.817.830.241.128.7
Zephyr-7B-β*7B32.143.033.042.537.7
PMC-LLaMA-7B7B26.472.926.625.537.9
Falcon-7B7B23.665.331.821.035.4
Gemma-2B2B27.660.827.730.636.7
BioMedLM-2.7B2.7B23.855.232.230.635.5
BioGPT-Large1.5B21.660.133.131.336.5
MedLLM (SFT)0.1B29.757.933.926.637.0
MedLLM (DPO)0.1B32.458.234.928.138.4

* Instruction-tuned baselines used with released weights.

How to use

The model uses custom architecture code shipped in this repository, so pass trust_remote_code=True. The tokenizer is a raw SentencePiece model, loaded with the sentencepiece package rather than AutoTokenizer.

pip install transformers sentencepiece torch

Basic forward pass

import torch
import sentencepiece as spm
from huggingface_hub import hf_hub_download
from transformers import AutoModelForCausalLM

repo = "maxxrichard/medllm-dpo-medmcqa"

model = AutoModelForCausalLM.from_pretrained(repo, trust_remote_code=True).eval()
sp = spm.SentencePieceProcessor(model_file=hf_hub_download(repo, "tokenizer.model"))

ids = torch.tensor([sp.encode("What is the mechanism of action of metformin?")])
with torch.no_grad():
    logits = model(ids).logits          # (batch, seq_len, 32000)

Multiple-choice scoring (how the model is evaluated)

The model is trained and evaluated as an option ranker, not a free-text generator. Score each candidate answer by the log-probability the model assigns to it after the question, and pick the best one:

import torch
import torch.nn.functional as F

def option_logprob(prompt: str, option: str) -> float:
    """Sum of log-probs of the option tokens, conditioned on the prompt."""
    p_ids = sp.encode(prompt)
    o_ids = sp.encode(option)
    ids = torch.tensor([p_ids + o_ids])[:, :512]
    with torch.no_grad():
        logp = F.log_softmax(model(ids).logits[0, :-1].float(), dim=-1)
    targets = ids[0, 1:]
    start = len(p_ids) - 1
    return logp[torch.arange(start, targets.numel()), targets[start:]].sum().item()

question = "A 45-year-old man presents with polyuria, polydipsia and weight loss. Fasting plasma glucose is 180 mg/dL. Which drug is the first-line oral therapy?"
options = ["Metformin", "Glibenclamide", "Insulin", "Pioglitazone"]
letters = ["A", "B", "C", "D"]

prompt = question + "\n" + "\n".join(f"{l}. {o}" for l, o in zip(letters, options)) + "\nAnswer:"
scores = [option_logprob(prompt, " " + l) for l in letters]
print(letters[scores.index(max(scores))])

The exact prompt templates used in the paper, cyclic permutation of the options to remove position bias, and ensembling over several templates all affect the numbers; the protocol above is a minimal reproduction of the top-token scoring.

Intended use and limitations

Intended use. Research on small-scale domain-specific language models, medical multiple-choice QA benchmarking, and as a sub-billion-parameter baseline. The model is released to characterise the sub-billion regime of medical LMs, which prior open work leaves uncharted.

Out of scope. This model is not a medical device and must not be used for diagnosis, treatment decisions, patient-facing advice or any clinical use. Its outputs have not been validated for safety, factual accuracy or absence of harmful content.

Limitations.

  • Trained and evaluated as a multiple-choice ranker; free-form generation quality is not assessed and is expected to be poor.
  • Limited breadth of encoded medical knowledge at 0.1B parameters. On knowledge-recall clinical vignettes (MedQA) the model stays near the task floor.
  • 512-token context window.
  • Each checkpoint is specialised for one benchmark format; transfer to other formats is only shown for MedMCQA → MMLU-Medical.
  • English only. Training data is web text and may contain biases and inaccuracies.

Citation

@misc{rahman2026medllm,
      title={MedLLM: An Open Medical Language Model at the Sub-Billion Scale},
      author={Maxx Richard Rahman and Asim Ahmed and Mihan Mohagheghzadeh and Wolfgang Maass},
      year={2026},
      eprint={2607.27490},
      archivePrefix={arXiv},
      primaryClass={cs.AI},
      url={https://arxiv.org/abs/2607.27490},
}

Authors

Maxx Richard Rahman (corresponding author), Asim Ahmed, Mihan Mohagheghzadeh and Wolfgang Maass — German Research Center for Artificial Intelligence (DFKI) and Saarland University, Germany.

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers

Нельзя запустить

Модели нужен код из репозитория; автор пока не в списке доверенных организаций.

Класс архитектуры
MedLLMForCausalLM
Ревизия весов
fddd2b6

0 моделей