BioMedLM 完整教學
Repository: https://github.com/stanford-crfm/BioMedLM Stars: 640 | Forks: 66 | Language: Python Tags: biomedical, LLM, Stanford Model Hub: https://huggingface.co/stanford-crfm/pubmedgpt Blog: https://crfm.stanford.edu/2022/12/15/pubmedgpt.html
2. 核心架構
2.1 整體架構圖
graph TB
subgraph "Pre-training Pipeline"
A["PubMed Abstracts
+ PubMed Central Full-text"] --> B["自訂 BPE Tokenizer
(vocab=28,896)"]
B --> C["GPT-2 2.7B 架構
(MosaicML Composer)"]
C --> D["BioMedLM
Pre-trained Checkpoint"]
end
subgraph "Fine-tuning Pipeline"
D --> E["NLU: Sequence Classification
(PubMedQA / BioASQ)"]
D --> F["NLU: Multiple Choice
(MedQA-USMLE)"]
D --> G["NLG: Text Generation
(MeQSum Summarization)"]
end
subgraph "Downstream 應用"
E --> H["生物醫學問答系統"]
F --> I["醫學考試評估"]
G --> J["醫學文獻摘要"]
D --> K["Synthetic Data Generation
(SDG 基礎模型)"]
end
subgraph "工具與依賴"
L["HuggingFace Transformers"] --> C
M["DeepSpeed CPU Offloading"] --> E & F & G
N["PyTorch Distributed"] --> E & F & G
end
style A fill:#e1f5fe
style D fill:#fff3e0
style K fill:#fce4ec
2.2 專案目錄結構
1BioMedLM/
2├── README.md # 專案說明與快速使用範例
3├── demo.py # 最簡推論 demo
4├── tokenize/
5│ └── train_bpe.py # 自訂 BPE tokenizer 訓練腳本
6├── finetune/
7│ ├── README.md # Fine-tuning 完整說明
8│ ├── setup/
9│ │ └── requirements.txt # 依賴套件
10│ ├── deepspeed/
11│ │ └── cpu_offload.json # DeepSpeed 記憶體優化設定
12│ ├── mc/ # Multiple Choice (多選題 QA)
13│ │ ├── README.md
14│ │ ├── preprocess_medqa.py # MedQA 資料前處理
15│ │ ├── run_multiple_choice.py # 多選微調主程式
16│ │ ├── run_experiments.py # 批次實驗腳本
17│ │ └── data/medqa_usmle_hf/ # MedQA-USMLE 範例資料
18│ ├── seqcls/ # Sequence Classification (序列分類)
19│ │ ├── README.md
20│ │ ├── preprocess_blurb_seqcls.py # BLURB 資料前處理
21│ │ ├── run_seqcls_gpt.py # 序列分類微調主程式
22│ │ └── data/ # PubMedQA / BioASQ 範例資料
23│ ├── textgen/ # Text Generation (文本生成)
24│ │ ├── data/meqsum/ # MeQSum 摘要任務資料
25│ │ └── gpt2/
26│ │ ├── finetune_for_summarization.py # 摘要微調
27│ │ ├── generate_demo.py # 生成 demo
28│ │ ├── run_generation_batch.py # 批次生成
29│ │ ├── sum_data_collator.py # 資料 collator
30│ │ └── sum_dataset.py # 資料集類別
31│ └── utils/
32│ ├── custom_modeling_gpt2.py # 自訂 GPT-2(加 Token Classification)
33│ ├── custom_modeling_gpt_neo.py # GPT-Neo 相容層
34│ └── hf_flash_gpt_2.py # Flash Attention 支援
2.3 Fine-tuning 任務架構
graph LR
subgraph "NLU Tasks"
direction TB
MC["Multiple Choice
(MedQA-USMLE)
4 選 1 醫學考題"]
SC["Sequence Classification
(PubMedQA / BioASQ)
yes/no/maybe 分類"]
end
subgraph "NLG Tasks"
direction TB
TG["Text Generation
(MeQSum)
醫療問題摘要"]
end
BM["BioMedLM
Pre-trained"] --> MC
BM --> SC
BM --> TG
MC -->|"MultipleChoiceModelOutput"| R1["Accuracy on
USMLE 4-option"]
SC -->|"SequenceClassifierOutput"| R2["Accuracy on
PubMedQA / BioASQ"]
TG -->|"Causal LM"| R3["ROUGE / BLEU
on MeQSum"]
style BM fill:#fff3e0
style MC fill:#e8f5e9
style SC fill:#e8f5e9
style TG fill:#e3f2fd
2.4 Tokenizer 設計
BioMedLM 使用自訂的 BPE(Byte-Pair Encoding; 位元組對編碼)tokenizer,這是整個系統的關鍵差異化設計:
| 項目 | BioMedLM Tokenizer | GPT-2 原版 |
|---|---|---|
| Vocab Size | 28,896 | 50,257 |
| 訓練語料 | PubMed 文獻 | WebText(通用網頁) |
| 生醫術語效率 | 高(如 methylation 為單一 token) | 低(可能拆成 3-4 tokens) |
| 一般英語效率 | 中等 | 高 |
較小的 vocab size 搭配領域特化語料,使得生物醫學文本的 tokenization 更有效率,同時減少 embedding 層的參數量。
3. 安裝與設定
3.1 環境需求
| 項目 | 最低需求 | 建議配置 |
|---|---|---|
| Python | 3.8+ | 3.8.12(官方測試版本) |
| PyTorch | 1.12+ | 1.12.1 with CUDA 11.3 |
| GPU | 1x 16GB | 8x A100 40GB(完整 fine-tuning) |
| RAM | 32GB | 64GB+ |
| 磁碟 | 20GB | 50GB+(含模型權重 + 資料集) |
3.2 安裝步驟
方法一:Conda 環境(官方推薦)
1# 建立 conda 環境
2conda create -n biomedlm python=3.8.12 pytorch=1.12.1 \
3 torchdata cudatoolkit=11.3 -c pytorch
4conda activate biomedlm
5
6# 克隆 repo
7git clone https://github.com/stanford-crfm/BioMedLM.git
8cd BioMedLM
9
10# 安裝 fine-tuning 依賴
11pip install -r finetune/setup/requirements.txt
方法二:uv 虛擬環境(現代化替代方案)
1# 使用 uv 建立隔離環境
2uv venv --python 3.8 .venv
3source .venv/bin/activate
4
5# 安裝核心依賴
6uv pip install torch==1.12.1+cu113 --extra-index-url https://download.pytorch.org/whl/cu113
7uv pip install transformers==4.24.0 datasets==2.6.1 \
8 huggingface-hub==0.10.1 wandb==0.13.5 \
9 fairscale==0.4.12 rouge-score==0.0.4 sacrebleu==2.0.0
10
11# 克隆 repo
12git clone https://github.com/stanford-crfm/BioMedLM.git
13cd BioMedLM
3.3 模型下載
1# 方法一:透過 HuggingFace Transformers 自動下載(推論時自動快取)
2python -c "
3from transformers import GPT2LMHeadModel, GPT2Tokenizer
4tokenizer = GPT2Tokenizer.from_pretrained('stanford-crfm/BioMedLM')
5model = GPT2LMHeadModel.from_pretrained('stanford-crfm/BioMedLM')
6print(f'Model parameters: {sum(p.numel() for p in model.parameters()):,}')
7"
8
9# 方法二:使用 huggingface-cli 預先下載
10pip install huggingface-hub
11huggingface-cli download stanford-crfm/pubmedgpt --local-dir ./biomedlm-weights
3.4 資料集準備
BioMedLM 的 fine-tuning 需要準備對應的 benchmark 資料集:
1# MedQA-USMLE(多選醫學考試題)
2# 從 https://github.com/jind11/MedQA 下載後放到:
3# finetune/mc/raw_data/medqa/data_clean/questions/US/4_options/
4
5# 前處理
6cd finetune/mc
7python preprocess_medqa.py
8# 產出 → data/medqa_usmle_hf/{train,dev,test}.json
9
10# PubMedQA / BioASQ(序列分類)
11# PubMedQA 從 https://pubmedqa.github.io/ 下載
12# BioASQ 從 http://www.bioasq.org/ 下載
13# 放到 finetune/seqcls/raw_data/blurb/data_generation/data/
14
15cd ../seqcls
16python preprocess_blurb_seqcls.py
17# 產出 → data/{pubmedqa_hf,bioasq_hf}/{train,dev,test}.json
3.5 依賴版本鎖定
以下是官方 requirements.txt 的完整依賴清單:
1datasets==2.6.1
2fairscale==0.4.12
3huggingface-hub==0.10.1
4rouge-score==0.0.4
5sacrebleu==2.0.0
6transformers==4.24.0
7wandb==0.13.5
注意:這些版本鎖定在 2022 年末,部分套件已有較新版本。若搭配較新的 PyTorch(2.x)使用,可能需要調整
transformers版本至 4.30+ 並測試相容性。
4. 使用方式與程式碼範例
4.1 範例一:基本推論與文本生成
這是最簡單的使用方式 – 載入預訓練模型,輸入生物醫學領域的 prompt,生成後續文本:
1"""
2BioMedLM 基本推論範例
3用途:生物醫學文本續寫、知識探索
4"""
5import torch
6from transformers import GPT2LMHeadModel, GPT2Tokenizer
7
8# ---------- 載入模型與 tokenizer ----------
9device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10tokenizer = GPT2Tokenizer.from_pretrained("stanford-crfm/BioMedLM")
11model = GPT2LMHeadModel.from_pretrained("stanford-crfm/BioMedLM").to(device)
12model.eval()
13
14# ---------- 生物醫學 prompt 範例 ----------
15prompts = [
16 "The mechanism of action of pembrolizumab involves",
17 "CRISPR-Cas9 gene editing in renal cell carcinoma has shown",
18 "The pharmacokinetics of oral semaglutide differ from subcutaneous formulation because",
19]
20
21for prompt in prompts:
22 input_ids = tokenizer.encode(prompt, return_tensors="pt").to(device)
23
24 with torch.no_grad():
25 output = model.generate(
26 input_ids,
27 do_sample=True,
28 max_length=150,
29 top_k=50,
30 top_p=0.95,
31 temperature=0.8,
32 num_return_sequences=1,
33 pad_token_id=tokenizer.eos_token_id,
34 )
35
36 generated = tokenizer.decode(output[0], skip_special_tokens=True)
37 print(f"\n{'='*60}")
38 print(f"Prompt: {prompt}")
39 print(f"Generated: {generated}")
重點解析:
- BioMedLM 使用
GPT2LMHeadModel而非自訂架構,與 HuggingFace 生態系完全相容 top_k=50, top_p=0.95, temperature=0.8是生物醫學文本生成的合理起始參數- 生成的文本會帶有 PubMed 文獻風格的措辭與結構
4.2 範例二:MedQA-USMLE 多選題 Fine-tuning
這是 BioMedLM 在醫學考試問答上的 fine-tuning 流程,展示如何將 pre-trained 模型調整為特定任務模型:
1#!/bin/bash
2# MedQA-USMLE Fine-tuning 腳本
3# 需求:至少 8x GPU(官方設定),可調整 nproc_per_node 與 batch_size
4
5cd finetune/mc
6
7# --- 設定參數 ---
8CHECKPOINT="stanford-crfm/BioMedLM" # 或本地路徑
9TOKENIZER="stanford-crfm/pubmed_gpt_tokenizer"
10NUM_DEVICES=8
11LEARNING_RATE=1e-5
12NUM_EPOCHS=5
13GRAD_ACCUM=4
14SEED=42
15RUN_NAME="biomedlm-medqa-usmle-v1"
16
17# --- 資料路徑 ---
18TASK="medqa_usmle_hf"
19DATADIR="data/${TASK}"
20OUTDIR="runs/${TASK}/BioMedLM"
21mkdir -p ${OUTDIR}
22
23# --- 啟動分散式訓練 ---
24python -m torch.distributed.launch \
25 --nproc_per_node=${NUM_DEVICES} \
26 --nnodes=1 \
27 --node_rank=0 \
28 run_multiple_choice.py \
29 --tokenizer_name ${TOKENIZER} \
30 --model_name_or_path ${CHECKPOINT} \
31 --train_file ${DATADIR}/train.json \
32 --validation_file ${DATADIR}/dev.json \
33 --test_file ${DATADIR}/test.json \
34 --do_train \
35 --do_eval \
36 --do_predict \
37 --per_device_train_batch_size 1 \
38 --per_device_eval_batch_size 1 \
39 --gradient_accumulation_steps ${GRAD_ACCUM} \
40 --learning_rate ${LEARNING_RATE} \
41 --warmup_ratio 0.5 \
42 --num_train_epochs ${NUM_EPOCHS} \
43 --max_seq_length 512 \
44 --bf16 \
45 --seed ${SEED} \
46 --data_seed ${SEED} \
47 --logging_first_step \
48 --logging_steps 20 \
49 --save_strategy no \
50 --evaluation_strategy steps \
51 --eval_steps 500 \
52 --run_name ${RUN_NAME} \
53 --output_dir ${OUTDIR} \
54 --overwrite_output_dir
重點解析:
per_device_train_batch_size=1+gradient_accumulation_steps=4= effective batch size 32(8 GPU x 1 x 4)warmup_ratio=0.5代表前半段訓練使用 warmup,這是 BioMedLM 團隊驗證過的設定max_seq_length=512限制序列長度以控制記憶體用量- 使用
torch.distributed.launch進行 Data Parallel(DP; 資料平行)訓練
單 GPU 調整(適用於資源有限的環境):
1# 單 GPU 版本(降低 batch 但增加 gradient accumulation)
2python -m torch.distributed.launch \
3 --nproc_per_node=1 \
4 --nnodes=1 \
5 --node_rank=0 \
6 run_multiple_choice.py \
7 --tokenizer_name stanford-crfm/pubmed_gpt_tokenizer \
8 --model_name_or_path stanford-crfm/BioMedLM \
9 --train_file data/medqa_usmle_hf/train.json \
10 --validation_file data/medqa_usmle_hf/dev.json \
11 --test_file data/medqa_usmle_hf/test.json \
12 --do_train --do_eval --do_predict \
13 --per_device_train_batch_size 1 \
14 --gradient_accumulation_steps 32 \
15 --learning_rate 1e-5 \
16 --warmup_ratio 0.5 \
17 --num_train_epochs 5 \
18 --max_seq_length 512 \
19 --bf16 \
20 --seed 42 \
21 --logging_steps 50 \
22 --save_strategy no \
23 --evaluation_strategy steps \
24 --eval_steps 200 \
25 --output_dir runs/medqa_single_gpu \
26 --overwrite_output_dir
4.3 範例三:醫學文本摘要生成(NLG Fine-tuning + Generation)
這個範例展示如何在 MeQSum(醫療問題摘要)任務上 fine-tune BioMedLM,然後批次生成摘要。這與 SDG 最直接相關 – 訓練一個能夠生成醫療文本的模型:
1#!/bin/bash
2# 步驟 1:Fine-tune for Summarization
3cd finetune/textgen/gpt2
4
5CHECKPOINT="stanford-crfm/BioMedLM"
6TOKENIZER="stanford-crfm/pubmed_gpt_tokenizer"
7RUN_DIR="runs/meqsum_biomedlm"
8
9python -m torch.distributed.launch \
10 --nproc_per_node=8 \
11 --nnodes=1 \
12 --node_rank=0 \
13 finetune_for_summarization.py \
14 --output_dir ${RUN_DIR} \
15 --model_name_or_path ${CHECKPOINT} \
16 --tokenizer_name ${TOKENIZER} \
17 --per_device_train_batch_size 1 \
18 --per_device_eval_batch_size 1 \
19 --save_strategy no \
20 --do_eval \
21 --train_data_file ../data/meqsum/train.source \
22 --eval_data_file ../data/meqsum/val.source \
23 --save_total_limit 2 \
24 --overwrite_output_dir \
25 --gradient_accumulation_steps 4 \
26 --learning_rate 5e-5 \
27 --warmup_ratio 0.5 \
28 --weight_decay 0.0 \
29 --seed 7 \
30 --evaluation_strategy steps \
31 --eval_steps 200 \
32 --bf16 \
33 --num_train_epochs 10 \
34 --logging_steps 100 \
35 --logging_first_step
1# 步驟 2:批次生成摘要
2CUDA_VISIBLE_DEVICES=0 python -u run_generation_batch.py \
3 --fp16 \
4 --max_source_length -1 \
5 --length 400 \
6 --model_name_or_path ${RUN_DIR} \
7 --num_return_sequences 5 \
8 --stop_token "[SEP]" \
9 --tokenizer_name ${RUN_DIR} \
10 --task_mode meqsum \
11 --control_mode no \
12 --tuning_mode finetune \
13 --gen_dir gen_results__tgtlen400__no_repeat_ngram_size6 \
14 --batch_size 9 \
15 --temperature 1.0 \
16 --no_repeat_ngram_size 6 \
17 --length_penalty -0.5
重點解析:
train.source/train.target為一行一筆的 paired 資料格式(原文 / 摘要)num_return_sequences=5生成 5 個候選摘要,可用於 SDG 中的多樣性採樣no_repeat_ngram_size=6防止重複 n-gram,提升生成品質length_penalty=-0.5鼓勵較長輸出(負值 = 偏好長文)- 此架構可直接改造為 SDG pipeline:將 source 換成結構化 prompt,target 換成想生成的合成資料格式
5. 在醫療 LLM / 文本 SDG 生態系中的定位
5.1 Bio-SDG Domain 6 定位
BioMedLM 屬於 Sub-domain A:Medical LLM Training Pipelines,與 MedicalGPT(完整 RLHF 訓練管線)和 BioGPT(微軟 PubMed 生成模型)並列為生物醫學領域 LLM 的三大開源基礎。
1Domain 6: 醫療 LLM 與文本 SDG
2├── A. Medical LLM Training Pipelines
3│ ├── MedicalGPT ─── 完整 RLHF pipeline(PT → SFT → RM → PPO/DPO)
4│ ├── BioGPT ─────── Microsoft,PubMed pre-trained,347M
5│ └── BioMedLM ←──── Stanford CRFM,PubMed pre-trained,2.7B ★ 本教學
6│
7├── B. LLM-driven SDG Frameworks
8│ ├── distilabel ──── 用 LLM 生成 + 標註合成資料
9│ ├── SDG (hitsz) ─── 學術 SDG 方法論集合
10│ └── sdg_hub ─────── SDG 資源匯集平台
11│
12├── C. Radiology Report Generation
13│ ├── R2GenGPT ────── 影像→報告 GPT 架構
14│ └── RadFact ─────── 放射學事實驗證
15│
16└── D. Medical Dialogue Generation
17 └── GEML-MDG ────── 醫病對話生成
5.2 BioMedLM 的獨特價值
| 維度 | BioMedLM | BioGPT | MedicalGPT |
|---|---|---|---|
| 參數量 | 2.7B | 347M | 依基底模型而定 |
| 架構 | GPT-2 | GPT-2 | LLaMA / ChatGLM 等 |
| 訓練語料 | PubMed only | PubMed only | 通用 + 醫療混合 |
| 訓練方式 | Pre-training from scratch | Pre-training from scratch | RLHF pipeline |
| 開源程度 | 權重 + 訓練碼 + tokenizer | 權重 + 推論碼 | Pipeline 框架 |
| 強項 | 中型模型 benchmark 冠軍 | 輕量推論 | 對話系統建構 |
BioMedLM 的核心差異化:它是目前開源界在 2.7B 規模下,唯一提供完整「tokenizer 訓練 + pre-training + 多任務 fine-tuning」全流程原始碼的生物醫學 LLM。
5.3 作為 SDG 基礎模型的價值
BioMedLM 在 SDG 管線中可以扮演以下角色:
- Synthetic Training Data Generator:fine-tune 後作為合成醫學問答、摘要、臨床筆記的生成引擎
- Domain-specific Evaluator:用其 perplexity 評估合成資料的生物醫學真實度
- Reward Model Backbone:用於 RLHF 流程中的 reward model 基底
- Distillation Teacher:作為更小模型的知識蒸餾來源
5.4 Blue Ocean 機會
BioMedLM 目前的 fine-tuning 範例僅涵蓋 QA 與摘要,以下是尚未被充分開發的 SDG 應用方向:
| Blue Ocean | 說明 | 難度 |
|---|---|---|
| 合成臨床筆記生成 | Fine-tune on de-identified clinical notes → 生成訓練用合成 EHR 敘述 | 中 |
| 藥物安全報告 SDG | 生成 FAERS 風格的 adverse event narratives | 中高 |
| Pre-IND 文件草稿 | 生成 IND application 各 section 的初稿文本 | 高 |
| Patent Claim 擴寫 | 從 disclosure memo 生成 claim variations | 高 |
| 多語言醫學 SDG | 平行生成中英雙語醫學文本 | 中 |
6. 與其他工具的整合
6.1 與 distilabel 整合(LLM-driven SDG)
BioMedLM 可作為 distilabel 的 local LLM backend,用於生成與標註合成生物醫學資料:
1"""
2BioMedLM + distilabel 整合概念
3用途:以 BioMedLM 作為 distilabel 的生成引擎,
4 批量產出合成生物醫學 QA pairs
5"""
6from transformers import pipeline
7
8# 建立 HuggingFace pipeline(distilabel 可直接使用)
9biomedlm_generator = pipeline(
10 "text-generation",
11 model="stanford-crfm/BioMedLM",
12 device=0,
13 max_length=256,
14 do_sample=True,
15 top_p=0.92,
16 temperature=0.85,
17)
18
19# 模擬 distilabel-style prompt 模板
20PROMPT_TEMPLATE = """Generate a biomedical question-answer pair about {topic}.
21
22Question: {seed_question}
23Answer:"""
24
25# 批次生成
26topics = [
27 {"topic": "PD-1 checkpoint inhibitors", "seed_question": "What is the mechanism of action of nivolumab?"},
28 {"topic": "mRNA vaccine technology", "seed_question": "How does lipid nanoparticle delivery work?"},
29 {"topic": "CRISPR therapeutics", "seed_question": "What are the off-target effects of Cas9?"},
30]
31
32for item in topics:
33 prompt = PROMPT_TEMPLATE.format(**item)
34 result = biomedlm_generator(prompt, num_return_sequences=3)
35 for i, r in enumerate(result):
36 print(f" Candidate {i+1}: {r['generated_text']}")
37 print()
6.2 與 AIKT Pipeline 整合
1AIKT Pipeline 整合路徑
2━━━━━━━━━━━━━━━━━━━━━━
3paper-search (Layer 9)
4 │ 搜尋 PubMed 文獻
5 ▼
6docling (Layer 8)
7 │ PDF → Markdown 全文
8 ▼
9BioMedLM fine-tune
10 │ 在領域文獻上 fine-tune
11 ▼
12paper-qa-lite (Layer 10)
13 │ 用 fine-tuned BioMedLM 做 RAG backbone
14 ▼
15quarkdown (Layer 7)
16 │ 排版成 HTML/PDF 報告
17 ▼
18Discord 交付
6.3 與 RadFact / R2GenGPT 整合
BioMedLM 可作為 radiology report generation 的 text backbone:
- R2GenGPT:替換其 GPT-2 decoder 為 BioMedLM,利用生醫特化 tokenizer 提升報告品質
- RadFact:用 BioMedLM 生成候選報告,再由 RadFact 做 factual verification
6.4 與 MedicalGPT RLHF Pipeline 整合
BioMedLM 可作為 MedicalGPT pipeline 的 base model:
- Stage 1 (PT):跳過,直接使用 BioMedLM pre-trained weights
- Stage 2 (SFT):在醫療對話資料上 supervised fine-tune
- Stage 3 (RM):訓練 reward model(可用 BioMedLM 自身作為 backbone)
- Stage 4 (PPO/DPO):RLHF 對齊
6.5 自訂 Tokenizer 訓練
當需要擴展到非 PubMed 領域(如中文醫學文獻、專利文本)時,可使用 BioMedLM 提供的 tokenizer 訓練腳本:
1"""
2基於 BioMedLM 的 tokenizer 訓練腳本
3用途:訓練領域特化 BPE tokenizer
4改編自:tokenize/train_bpe.py
5"""
6import json
7import os
8from tokenizers import (
9 Tokenizer, models, pre_tokenizers,
10 decoders, trainers, processors
11)
12
13# 自訂語料檔案路徑(一行一筆文本的 .txt 檔)
14input_files = [
15 "corpus/pubmed_abstracts.txt",
16 "corpus/clinical_notes.txt", # 加入臨床筆記
17 "corpus/fda_labels.txt", # 加入 FDA 藥物標籤
18]
19tokenizer_name = "my_biomedical_tokenizer"
20os.makedirs(tokenizer_name, exist_ok=True)
21
22# 初始化 BPE tokenizer
23tokenizer = Tokenizer(models.BPE())
24tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
25tokenizer.decoder = decoders.ByteLevel()
26tokenizer.post_processor = processors.ByteLevel(trim_offsets=True)
27
28# 訓練(可調整 vocab_size)
29trainer = trainers.BpeTrainer(
30 vocab_size=32000, # BioMedLM 原版用 28,896
31 min_frequency=2,
32 initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
33 special_tokens=["<|endoftext|>", "<pad>", "<sep>"],
34)
35tokenizer.train(input_files, trainer=trainer)
36
37# 儲存
38tokenizer.save(f"{tokenizer_name}/tokenizer.json", pretty=True)
39
40# 匯出 HuggingFace 格式
41with open(f"{tokenizer_name}/vocab.json", "w") as f:
42 vocab = json.loads(
43 open(f"{tokenizer_name}/tokenizer.json").read()
44 )["model"]["vocab"]
45 json.dump(vocab, f)
46
47with open(f"{tokenizer_name}/merges.txt", "w") as f:
48 merges = json.loads(
49 open(f"{tokenizer_name}/tokenizer.json").read()
50 )["model"]["merges"]
51 f.write("\n".join(merges))
52
53print(f"Tokenizer saved to {tokenizer_name}/")
54print(f"Vocab size: {tokenizer.get_vocab_size()}")
7. 優缺點分析
7.1 優點
| 優點 | 說明 |
|---|---|
| 完整開源 | 模型權重、tokenizer、pre-training 概念、fine-tuning 全流程程式碼完整公開 |
| 領域特化效果強 | 2.7B 參數在 PubMedQA、BioASQ、MedQA 上表現優於同規模通用模型 |
| HuggingFace 生態系相容 | 使用標準 GPT2LMHeadModel,可直接套用所有 HF 工具鏈 |
| 自訂 Tokenizer 開源 | 提供 tokenizer 訓練腳本,可重現或擴展到新領域 |
| Benchmark 資料格式範例 | 附帶 MedQA、PubMedQA、BioASQ、MeQSum 的格式範例 |
| 中等規模可控 | 2.7B 參數在單 GPU 上可推論,多 GPU 可 fine-tune,不需超大算力 |
| MosaicML Composer 訓練 | 使用高效率訓練框架,技術選型具參考價值 |
7.2 缺點
| 缺點 | 說明 |
|---|---|
| Pre-training 程式碼未完整公開 | Repo 僅提供 fine-tuning 碼,pre-training 細節需參考 blog 與 MosaicML |
| 依賴版本老舊 | 鎖定 transformers 4.24、PyTorch 1.12(2022 年末版本) |
| 無對話能力 | 純 causal LM,無 instruction tuning 或 chat alignment |
| 上下文長度受限 | 1024 tokens 的上下文窗口,不足以處理長文獻或複雜 prompt |
| 訓練語料僅 PubMed | 不含臨床筆記、FDA 文件、藥物標籤等非學術來源 |
| Flash Attention 支援初步 | hf_flash_gpt_2.py 存在但非官方整合,需手動啟用 |
| 無 RLHF / DPO 對齊 | 需額外搭配 MedicalGPT 等框架才能做人類偏好對齊 |
| 維護活躍度低 | 最近更新為 2026-05,但核心程式碼自 2023 年後未有重大更新 |
| DeepSpeed 設定基礎 | 僅提供 CPU offload 設定,未提供 ZeRO Stage 3 等進階設定 |
7.3 與替代方案的取捨
1選擇指南
2━━━━━━━━
3需要「輕量推論 + 快速原型」?
4 → BioGPT(347M,更小更快)
5
6需要「完整 RLHF 對話系統」?
7 → MedicalGPT(提供 PT→SFT→RM→PPO 全 pipeline)
8
9需要「中型模型 + 多任務 fine-tuning baseline」?
10 → BioMedLM(2.7B,benchmark 冠軍)★
11
12需要「生產等級 SDG 管線」?
13 → distilabel + BioMedLM 作為 backend
14
15需要「最新最大生醫模型」?
16 → 考慮 Med-PaLM / GPT-4 API(非開源,但能力更強)
7.4 實務建議
- 版本升級路徑:建議測試
transformers>=4.35+torch>=2.0的相容性,以獲得 Flash Attention 2 和更好的推論效能 - LoRA 微調替代:對於 GPU 記憶體有限的環境,可使用 PEFT/LoRA 取代全參數 fine-tuning,BioMedLM 的 GPT-2 架構完全支援
- SDG 應用起步:從 MeQSum 摘要生成任務開始,逐步擴展到自定義合成資料格式
- Tokenizer 擴展:若目標包含中文醫學文獻,建議重訓 tokenizer 加入中文字元
- Evaluation 策略:使用 BioMedLM 的 perplexity 作為合成資料品質的快速篩選指標
一行總結:BioMedLM 是 Stanford CRFM 推出的 2.7B 生物醫學特化 GPT-2 模型,提供從 tokenizer 訓練到多任務 fine-tuning 的完整開源流程,特別適合作為中型規模生物醫學 NLP 與 Synthetic Data Generation 的基礎模型。
Comments