/ Модель

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

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

medllm-dpo-pubmedqa

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

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

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

Небольшая англоязычная медицинская модель для ранжирования ответов «да/нет/возможно» на вопросы PubMedQA по аннотациям статей.

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

Модель предназначена для выбора ответа «да», «нет» или «возможно» на вопросы по аннотациям PubMed. Её следует применять как ранжировщик вариантов: сравнивать логарифмические вероятности ответов, а не полагаться на свободную генерацию текста. В zero-shot оценке на экспертно размеченной выборке PubMedQA из 500 вопросов точность составила 58,2 ± 1,8%. Модель рассчитана на английский язык и контекст до 512 токенов.

Это исследовательская базовая модель для изучения небольших специализированных языковых моделей и тестирования медицинского QA. Она не является медицинским устройством и не предназначена для диагностики, лечения, клинических решений или советов пациентам; её безопасность и фактическая точность не проверены. При 100 млн параметров охват медицинских знаний ограничен, а качество свободной генерации отдельно не оценивалось. Лицензия — Apache-2.0.

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

  • выбор ответа на вопрос PubMedQA по аннотации статьи
  • сравнение вариантов ответа «да», «нет» и «возможно» по вероятности
  • бенчмаркинг небольших медицинских языковых моделей
  • исследование влияния SFT и DPO на медицинский QA

Ограничения

Модель обучена и оценивалась как ранжировщик вариантов, а качество свободной генерации не проверялось; при 100,29 млн параметров её медицинские знания ограничены. Не используйте её для диагностики, лечения, клинических решений или советов пациентам; контекст ограничен 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 — PubMedQA

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 PubMedQA (context-grounded yes / no / maybe questions over PubMed abstracts). 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 PubMedQA 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 PubMedQA (this checkpoint)

Training examples211,269
SFT6,000 steps, batch 64, 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 (%)
PubMedQAPubMedQA (expert-labelled, reasoning-required, 500 items)58.2 ± 1.8

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-pubmedqa"

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 = "Context: In a randomized trial of 2,000 patients, low-dose aspirin reduced the incidence of myocardial infarction by 22% compared with placebo, with no significant increase in major bleeding.\nQuestion: Does low-dose aspirin reduce the risk of myocardial infarction?"
options = ["yes", "no", "maybe"]
letters = ["A", "B", "C"]

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
Ревизия весов
5b6767a

0 моделей