/ Модель

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

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

medllm-dpo-medqa

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

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

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

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

MedLLM-DPO-MedQA — медицинская языковая модель, разработанная Максом Ричардом Рахманом, Асимом Ахмедом, Миханом Мохагегзаде и Вольфгангом Маасом из DFKI и Саарского университета. Это decoder-only Transformer с архитектурой в стиле OLMo-2 и 100,29 млн параметров, обученный с нуля на общих текстах, затем дообученный на медицинском веб-корпусе MedFineWeb и выровненный посредством SFT и DPO на обучающей части MedQA.

Модель предназначена для исследовательских экспериментов и бенчмаркинга медицинских вопросов с четырьмя вариантами ответа в стиле USMLE. Она оценивает варианты по логарифмической вероятности и выбирает наиболее вероятный; показатель на тесте MedQA составляет 28,1%. Контекстное окно — 512 токенов, язык — английский. Свободная генерация не оценивалась и, по данным карточки, ожидается слабой; модель показывает низкие результаты на клинических виньетках, а её медицинские знания ограничены небольшим размером.

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

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

  • ранжирование четырёх вариантов ответа в медицинских задачах MedQA
  • сравнение небольших медицинских языковых моделей на бенчмарках
  • исследование влияния размера модели на ответы по клиническим виньеткам

Ограничения

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

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

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

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

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

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

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

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

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

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

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

Открыть на Hugging Face

MedLLM-DPO — MedQA

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 MedQA (USMLE-style 4-option clinical vignettes). 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 MedQA 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 MedQA (this checkpoint)

Training examples10,178
SFT4,000 steps, batch 8, LR 2e-5, label-prediction loss over all options
DPO500 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 (%)
MedQAMedQA USMLE 4-option (test, 1,273 items)28.1 ± 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-medqa"

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 62-year-old woman presents with sudden-onset crushing chest pain radiating to the left arm. ECG shows ST elevation in leads II, III and aVF. Which coronary artery is most likely occluded?"
options = ["Left anterior descending artery", "Right coronary artery", "Left circumflex artery", "Left main coronary artery"]
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
Ревизия весов
b14d5a3

0 моделей