NVIDIA-BioNeMo/bionemo-framework 完整教學
一句話定位:NVIDIA Clara BioPharma 平台的訓練引擎開源層 — GPU 高度最佳化的 recipe 與工具集,把 NVIDIA 在 LLM 上的全套絕活(TransformerEngine FP8/MXFP8/NVFP4 低精度、megatron-FSDP、context parallel、sequence packing、Hopper / Blackwell 架構優化)搬到 biopharma 領域:從 蛋白質(ESM-2 8M→15B、AMPLIFY)、單細胞 RNA(Geneformer)、基因體(Evo2 1B→40B,1M+ nt context)、codon(CodonFM 1B/5B)、生成式小分子(MoCo 系列 interpolant:DDPM/VDM/CFM/D3PM/MDLM/DFM),到通用 LLM(Llama3 144K context、Mixtral MoE、Qwen2.5/3)的 biopharma 適配版。整合 NVIDIA AI 全家桶(Megatron-Bridge / Automodel / TransformerEngine / NIM),是 NVIDIA/BioNeMo Blueprint hub 的底層引擎。
適合:要在 NVIDIA H100 / B200 / GB300 上跑生科 SOTA 訓練的工程師與研究員;要把 ESM-2 / AMPLIFY fine-tune 到自家 lab 序列;要做大規模單細胞 / 基因體 foundation model;要做分子生成擴散模型;要建構生科 production 訓練 pipeline。
不適合:純 CPU 環境(雖然推論可在 CPU,但訓練必須 GPU);只要 inference 不要訓練(→ 直接用 HuggingFace API 或 BioNeMo NIM);做結構預測為主(→ 改看 OpenFold / AlphaFold);要 ready-to-go SaaS(→ 改用 NVIDIA NIM Microservices)。
⚠️ 重要法律提醒:repo 本身 Apache-2.0,但 container image 在 NGC 上可能附加 NVIDIA AI Enterprise 條款;模型權重(如 ESM-2、CodonFM)多為 NVIDIA Open Model License (NOML) 或上游條款(ESM-2 原 Meta CC-BY-NC),商用前須個別審。第三方授權見
LICENSE/third_party.txt(71.9K,含上百個上游)。
目錄
- 專案定位
- 安裝指南
- 核心架構解析
- Helper Scripts 詳細用法
- 應用場景:6 條 end-to-end pipeline
- 資安掃描報告
- FAQ
- 進階技巧
- 整合進其他工作流
- 重點摘要 Checklist
- 進一步閱讀
1. 專案定位
1.1 這是什麼
NVIDIA-BioNeMo/bionemo-framework 是 NVIDIA Clara BioPharma 平台的核心開源訓練框架。它不是「一個模型」、也不是「一個 SaaS」、也不是「一個 Blueprint」,而是:
1┌─────────────────────────────────────────────────────────────────┐
2│ BioNeMo Framework — 訓練引擎開源層 │
3├─────────────────────────────────────────────────────────────────┤
4│ (1) bionemo-recipes/ ─→ self-contained pretrain / SFT / LoRA │
5│ recipes(每個 folder 獨立可拉到 Colab) │
6│ │
7│ (2) sub-packages/ ─→ 可獨立 pip install 的 utility 庫 │
8│ (scdl / moco / noodles / scspeedtest) │
9│ │
10│ (3) NVIDIA TE 加速層 ─→ FP8 / MXFP8 / NVFP4 / sequence packing │
11│ / context parallel / megatron-FSDP │
12│ │
13│ (4) 預建 container ─→ nvcr.io/nvidia/clara/bionemo-framework │
14│ (nightly + tag 版本) │
15│ │
16│ (5) Brev.dev 一鍵雲 ─→ README 直接掛 deploy button │
17└─────────────────────────────────────────────────────────────────┘
技術上它把 三層東西 整合在一起:
- 模型實作:把蛋白質 / 單細胞 / 基因體 / 小分子的 SOTA 開源模型,用 TransformerEngine 改寫一次,得到 TE 加速版(modeling_esm_te.py / modeling_llama_te.py 等)。
- 訓練 recipe:用三種主流 training stack(native PyTorch / HuggingFace Accelerate / megatron-FSDP)各寫一份 training loop,使用者選熟悉的那一份起手。
- 資料工具:因應生科特殊資料格式(FASTA / h5ad single-cell / parquet sequence),提供
bionemo-scdl/bionemo-noodles等 high-perf I/O 庫。
1.2 名稱由來與歷史
| 項目 | 內容 |
|---|---|
| BioNeMo | Bio(生物學)+ NeMo(NVIDIA Neural Modules,NVIDIA 主力訓練框架) |
| 上一代 | BioNeMo v1 用 PyTorch Lightning + NeMo,與 LLM 訓練 stack 高度耦合 |
| v2 重構 | 2025 起轉成「self-contained recipes」設計:每個 recipe 一個 folder、獨立 requirements、不依賴 monorepo 其它部分(README 明示「does not depend on any other code in the top-level bionemo-framework repository」) |
| 為什麼這樣改 | 1) 讓使用者只拉一個 recipe 就能跑(Colab 友善) 2) 不同 recipe 用不同 training stack 不會打架 3) Code 可讀性 ↑(每個 recipe 一個 main.py) |
| 目前 v2.7 | 2025-10-01 release;本教學涵蓋 v2.7 主線 + 2026-06 main 分支新增(Mixtral / Qwen / Sparse Autoencoder / NVFP4) |
1.3 在 NVIDIA Clara BioPharma 與 NVIDIA AI 生態中的位置
1 NVIDIA AI Enterprise(商業授權層)
2 │
3 ┌───────────────────┼───────────────────┐
4 ▼ ▼ ▼
5 NVIDIA AI Blueprints NVIDIA NIM Microservices NGC Container Registry
6 (產業解決方案) (API-as-a-Service) (nvcr.io)
7 │ │ │
8 └───────────────────┼───────────────────┘
9 ▼
10 NVIDIA Clara BioPharma(生科垂直)
11 │
12 ┌───────────────────────┼───────────────────────┐
13 ▼ ▼ ▼
14 NVIDIA/BioNeMo bionemo-framework NVIDIA/digital-biology
15 (Blueprint hub (訓練引擎,本 repo) -examples
16 / cookbook) (泛數位生物範例)
17 │ │ │
18 └───────────────────────┼───────────────────────┘
19 ▼
20 共享底層(與 NVIDIA-NeMo LLM stack 同源)
21 │
22 ┌────────────────┬────────┴────────┬────────────────┐
23 ▼ ▼ ▼ ▼
24TransformerEngine Megatron-Bridge Megatron-FSDP Megatron-LM
25(FP8/MXFP8/NVFP4) (checkpoint (5D parallel) (up-stream)
26 互轉橋接層)
27 │
28 ▼
29 NVIDIA-NeMo/Nemotron(LLM hub)— 同源、不同領域
30 NVIDIA-NeMo/Automodel(HF 加速橋接)
31 NVIDIA-NeMo/RL(RLHF / GRPO)
32 NVIDIA-NeMo/Curator(資料清洗)
對應關係(給看過 PyTorch 生態的人):
| PyTorch 生態 | NVIDIA Clara BioPharma 生態 |
|---|---|
| PyTorch core | TransformerEngine + Megatron-LM |
| PyTorch examples | bionemo-framework(本 repo) |
| HuggingFace transformers | NVIDIA/BioNeMo Blueprints |
| HuggingFace inference endpoints | BioNeMo NIM Microservices |
| Lightning AI Studio | Brev.dev launchable(README 內建按鈕) |
對應關係(給 NVIDIA NLP 領域人):
| NLP / LLM 領域 | BioPharma 領域 |
|---|---|
| NVIDIA-NeMo/Nemotron(hub) | NVIDIA/BioNeMo(Blueprint hub) |
| NVIDIA-NeMo/Automodel(HF 加速) | bionemo-framework(HF + Megatron-Bridge 雙橋) |
| Megatron-LM training | bionemo-recipes/recipes/*_native_te |
| TRT-LLM / vLLM 推論 | bionemo-recipes/recipes/vllm_inference |
與閉源 / 社群競品:
| 競品 | 性質 | 與本 repo 關係 |
|---|---|---|
| DeepMind AlphaFold 3 | 閉源(webserver only) | 不重疊;AlphaFold 做結構預測,本 repo 主力是序列 / 基因體 / 單細胞語言模型 |
| Meta ESM / ESMFold | 開源 weights,但 fine-tune 工具有限 | 本 repo 提供 NVIDIA TE 加速版 ESM-2,並支援 fine-tune / LoRA / FP8 量化 |
| OpenFold / OpenFold3 | 社群版 AlphaFold | 互補;OpenFold 做結構,本 repo 做序列 / 生成 |
| Boltz-1 / RoseTTAFold | 社群結構預測 | 互補 |
| InstaDeep BoltzGen / NuPL | 社群 protein gen | 重疊(蛋白質設計),可比較 |
| Salesforce ProGen | 蛋白質生成 | 重疊(語言模型風格生成) |
1.4 跟既有 NVIDIA 教學的關係
本 repo 之前已產出的 NVIDIA 知識(同 inbox/):
| 已產出 tutorial | 與本 repo 關係 |
|---|---|
2026-06-02-tutorial-Nemotron.md | Nemotron 是 LLM hub(產業解決方案層中的通用 LLM);本 repo 是 BioPharma 版本。Nemotron 用 Megatron-Bridge / TransformerEngine;本 repo 完全共用同一套底層 |
2026-06-02-tutorial-Cosmos.md | Cosmos 是 物理 AI / 機器人 world model;本 repo 是 biopharma。彼此資料不重疊,但都用 NVIDIA AI Enterprise 平台 + TransformerEngine |
2026-06-02-tutorial-Megatron-Bridge.md | 本 repo 的 evo2_megatron recipe 直接呼叫 Megatron-Bridge,需要熟讀 Megatron-Bridge 才能改 evo2 訓練 |
2026-06-02-tutorial-Automodel.md | 本 repo 的 *_accelerate_te recipe(如 esm2_accelerate_te)走 HuggingFace Accelerate 路徑,與 Automodel 的設計思路一致 |
2026-06-02-NVlabs-explorer-guide.md | NVlabs 是 NVIDIA Research GitHub org;本 repo 屬於 NVIDIA-BioNeMo(NVIDIA Clara 產品線),不是 NVlabs,但部分技術(如 SAE for ESM2)來自 NVIDIA Research |
如果你已經讀過 Nemotron tutorial,重點移過來這份只需注意:
- 資料不一樣:FASTA 蛋白質 / h5ad 單細胞 / parquet 序列(而非自然語言 token)
- 特殊工具:
bionemo-scdl(單細胞)、bionemo-noodles(FASTA 高效讀寫)、bionemo-moco(分子 interpolant) - 特殊 model class:ESM-2 / AMPLIFY / Evo2 / Geneformer / CodonFM
- 特殊評估:MFU 算法在生科序列上要特別處理(issue #1561 的
pad_to_multiple_of問題)
1.5 三句話 elevator pitch
1「我要在 H100 上 fine-tune ESM-2 15B 做我家蛋白質序列,要 FP8 加速 + LoRA。」
2→ 拉 bionemo-recipes/recipes/esm2_peft_te,改 config.yaml,跑 train_*.py。
3
4「我要 pretrain 自家 50M cell scRNA-seq foundation model。」
5→ 用 bionemo-scdl 做 memory-mapped data loading,
6 參考 geneformer_native_te_mfsdp_fp8 recipe 的 mFSDP + FP8 training loop。
7
8「我要設計 small molecule diffusion,但不想自己刻 DDPM/CFM。」
9→ pip install bionemo-moco,繼承 Interpolant base class,套 DDPM/VDM/CFM/D3PM。
2. 安裝指南
2.1 五種安裝方式
| 方法 | 對象 | 時間 | 注意 |
|---|---|---|---|
| A NGC container(推薦) | 內部 H100 / DGX | 5–10 min(pull) | nightly 或 tag 版本 |
| B 本地 build container | 自家 CI / 自訂 base | 30–60 min | 需要 --ulimit nofile=65535:65535 |
| C VSCode devcontainer | 開發者 | 30 min(首次) | 適合互動式 debug |
| D Brev.dev launchable | 試用 / 教學 | 5 min | 雲端 A100,按 README 按鈕 |
| E Colab(Quick Start) | 入門體驗 | 10 min | 需 A100(T4 太慢且 OOM) |
2.2 方法 A:NGC container
1# 拉 nightly(每天 build,含最新功能)
2docker pull nvcr.io/nvidia/clara/bionemo-framework:nightly
3
4# 或拉特定 tag(生產建議鎖版本)
5docker pull nvcr.io/nvidia/clara/bionemo-framework:2.7
6
7# 跑起來
8docker run --rm -it \
9 --gpus=all --ipc=host \
10 --ulimit memlock=-1 --ulimit stack=67108864 \
11 -v $PWD:/workspace \
12 nvcr.io/nvidia/clara/bionemo-framework:nightly \
13 /bin/bash
為什麼這些 flag 必要:
--gpus=all:交出全部 GPU 給 container--ipc=host:PyTorch DataLoader 多 worker 共享 SHM--ulimit memlock=-1:解除鎖頁記憶體限制(NCCL 需要)--ulimit stack=67108864:64 MB stack(NCCL nvls 啟動需要)
2.3 方法 B:本地 build container
1git clone https://github.com/NVIDIA-BioNeMo/bionemo-framework.git
2cd bionemo-framework
3
4# 建議用 buildx(支援多 stage / 多平台)
5docker buildx build . -t my-bionemo:latest
6
7# 若遇 "No file descriptors available (os error 24)"
8docker buildx build . -t my-bionemo:latest --ulimit nofile=65535:65535
build 期間會:
- 從 PyTorch container 起手(README 提及 26.03/26.04 升級紀錄)
- 編譯 TransformerEngine(最慢,CUDA kernel 多)
- 安裝
sub-packages/*為 editable mode - 安裝
bionemo-recipes/*相依
2.4 方法 C:VSCode devcontainer
- 安裝 VSCode + Dev Containers 擴充套件
- 開啟
bionemo-framework/資料夾 - 跳出「Reopen in Container」→ 點下去
- 等首次 build(建議先用方法 B 在 CLI build 一次,devcontainer 會自動用本地 cache)
進到 devcontainer 後,sub-packages 不會自動裝,要手動:
1uv pip install -e ./sub-packages/bionemo-core
2uv pip install -e ./sub-packages/bionemo-scdl
3uv pip install -e "./sub-packages/bionemo-recipeutils[basecamp]"
4# 你也可以用 pip install -e ...,效果一樣
2.5 方法 D:Brev.dev launchable
直接點 README 中央的 deploy button → Brev.dev 會:
- 開一個 H100 / A100 instance
- 自動 pull nightly container
- 給你一個 JupyterLab URL
適合:演講 demo / 內訓 / 趕 deadline 沒空 setup。
2.6 方法 E:Colab Quick Start(最簡入門)
1!git clone https://github.com/NVIDIA/bionemo-framework.git
2%cd bionemo-framework/bionemo-recipes/recipes/esm2_native_te/
3
4# TE wheel 太大從 PyPI 慢,故 README 提供 Google Drive 鏡像
5!curl -L -o transformer_engine_torch-2.8.0-cp312-cp312-linux_x86_64.whl \
6 "https://drive.google.com/uc?export=download&id=1Oz6dkkIMahv3LN_fQhhQRolZ3m-sr9SF"
7!pip install --no-build-isolation transformer-engine \
8 transformer_engine_torch-2.8.0-cp312-cp312-linux_x86_64.whl
9
10!pip install -r requirements.txt
11!python train_ddp.py
⚠️ 必須 A100 等級;T4 OOM。
2.7 常見安裝坑
| 症狀 | 原因 | 解法 |
|---|---|---|
transformer_engine 編譯失敗 | nvcc < 12.x | 用 NGC container(已預裝) |
No file descriptors available (os error 24) | docker daemon limit | --ulimit nofile=65535:65535 |
| Geneformer / CodonFM 載入慢 | HF cache 缺 | 設 HF_HOME=/large-disk/hf-cache |
| FP8 訓練 NaN | 硬體未達 SM 9.0 | 改用 BF16;只有 H100/B200/GB300 支援 FP8 |
| MXFP8 NaN | 必須 Blackwell(SM 10.x) | 退回 FP8 / BF16 |
| Evo2 訓練無法 reproduce | 已知 issue #1493 | 鎖 seed + warp 版本 |
| AMPLIFY pkg_resources 錯 | setuptools 82+ break | 用 #1574 fix 後版本 |
3. 核心架構解析
3.1 兩大 directory 的設計差別
flowchart TB
Repo[bionemo-framework] --> Recipes[bionemo-recipes/]
Repo --> Subs[sub-packages/]
Repo --> Docs[docs/]
Repo --> Ci[ci/]
Recipes --> Models[models/]
Recipes --> RecipeDir[recipes/]
Recipes --> Interp[interpretability/]
Models --> ESM2M[esm2 model]
Models --> Amp[amplify]
Models --> Llama3M[llama3]
Models --> Gene[geneformer]
Models --> Codon[codonfm]
Models --> Mix[mixtral]
Models --> Qwen[qwen]
RecipeDir --> ESM2R[esm2_native_te / accelerate_te / peft_te]
RecipeDir --> Llama3R[llama3_native_te]
RecipeDir --> Evo2R[evo2_megatron]
RecipeDir --> CodonR[codonfm_native_te / ptl_te]
RecipeDir --> Eden[eden_megatron]
RecipeDir --> Genef[geneformer_native_te_mfsdp_fp8]
RecipeDir --> Vit[vit]
RecipeDir --> Vllm[vllm_inference]
RecipeDir --> Fp8a[fp8_analysis]
Interp --> SAE[sparse_autoencoders]
Subs --> Core[bionemo-core]
Subs --> Util[bionemo-recipeutils]
Subs --> MoCo[bionemo-moco]
Subs --> Nood[bionemo-noodles]
Subs --> Scdl[bionemo-scdl]
Subs --> Scsp[bionemo-scspeedtest]
Subs --> Saw[bionemo-size-aware-batching]
Subs --> Web[bionemo-webdatamodule]
classDef m fill:#dbeafe,stroke:#1e40af
classDef r fill:#fef3c7,stroke:#92400e
classDef s fill:#dcfce7,stroke:#166534
class ESM2M,Amp,Llama3M,Gene,Codon,Mix,Qwen m
class ESM2R,Llama3R,Evo2R,CodonR,Eden,Genef,Vit,Vllm,Fp8a r
class Core,Util,MoCo,Nood,Scdl,Scsp,Saw,Web s
設計重點:
models/放「TE 改寫過的 PreTrainedModel」— 重點是modeling_*_te.py+convert.py(HF↔TE checkpoint 互轉)+state.py(state dict mapping)。recipes/放「完整訓練腳本」— 重點是train_*.py(針對不同 training stack 一份),加上collator.py/dataset.py/quantization.py等共用 module。sub-packages/放「reusable utility 庫」— 是可以pip install bionemo-scdl獨立用的;recipe 內pip install -e .進來。
3.2 訓練 pipeline 全貌(資料 → tokenize → train → eval → export)
flowchart LR
A[Raw biological data
FASTA / h5ad / parquet] -->|bionemo-noodles
or bionemo-scdl| B[Preprocessed shards]
B -->|tokenizer
per recipe| C[Tokenized input]
C -->|collator.py
sequence packing| D[Packed batches]
D -->|TransformerEngine
FP8 / MXFP8 / NVFP4| E[Forward + Backward]
E -->|megatron-FSDP
or DDP / FSDP2| F[Distributed update]
F -->|checkpoint.py
DCP format| G[Checkpoint shards]
G -->|convert.py| H[HF format]
H -->|export.py| I[HuggingFace Hub]
H -->|vLLM / TRT-LLM| J[Inference deploy]
H -->|BioNeMo NIM| K[API microservice]
classDef data fill:#dbeafe,stroke:#1e40af
classDef train fill:#fef3c7,stroke:#92400e
classDef deploy fill:#dcfce7,stroke:#166534
class A,B,C,D data
class E,F,G train
class H,I,J,K deploy
3.3 模型分布(哪個 model 在 framework 裡長什麼樣)
flowchart TB
BF[bionemo-framework]
BF --> Protein[蛋白質 / Protein]
BF --> NucGen[核酸 / 基因體]
BF --> Single[單細胞 / scRNA-seq]
BF --> Mol[小分子 / Molecule]
BF --> GenLLM[通用 LLM 用於生科]
Protein --> ESM[ESM-2 8M to 15B
BERT 風格
FP8/MXFP8/NVFP4
CP / seq packing]
Protein --> AMP[AMPLIFY
蛋白質 BERT
FP8
seq packing WIP]
NucGen --> EVO[Evo2 1B to 40B
Striped Hyena SSM+Attn
1M plus nt context
via Megatron Bridge]
NucGen --> CFM[CodonFM 1B and 5B
codon-level transformer]
Single --> GFM[Geneformer
single-cell BERT
FP8 + mFSDP]
Single --> SCDL[bionemo-scdl
memory-mapped loader
替代 AnnData]
Mol --> MOCO[bionemo-moco
DDPM / VDM / CFM
D3PM / MDLM / DFM]
GenLLM --> L3[Llama3
144K context
GB300 NVL36]
GenLLM --> MX[Mixtral MoE
GroupedLinear + FP8/FP4]
GenLLM --> QW[Qwen2.5/3
TE + HF bi-dir convert]
classDef p fill:#fde68a,stroke:#92400e
classDef n fill:#bbf7d0,stroke:#166534
classDef s fill:#bfdbfe,stroke:#1e40af
classDef m fill:#fbcfe8,stroke:#9d174d
classDef l fill:#e9d5ff,stroke:#6b21a8
class ESM,AMP p
class EVO,CFM n
class GFM,SCDL s
class MOCO m
class L3,MX,QW l
3.4 NVIDIA AI Stack 整合(端到端從硬體到 API)
flowchart TB
HW[NVIDIA Hardware
H100 / B200 / GB300] --> CUDA[CUDA + cuBLAS / cuDNN]
CUDA --> TE[TransformerEngine
FP8 / MXFP8 / NVFP4 kernels]
TE --> MFSDP[megatron-FSDP
5D parallel]
TE --> MBR[Megatron-Bridge
checkpoint 互轉]
MFSDP --> BF[bionemo-framework recipes
本 repo]
MBR --> BF
BF --> HF[HuggingFace checkpoint]
BF --> DCP[Distributed Checkpoint]
HF --> VLLM[vLLM / TRT-LLM]
HF --> NIM[BioNeMo NIM
Microservice API]
DCP --> NEMO[NeMo / NeMo-RL
共用 LLM stack]
NIM --> DGX[NVIDIA DGX Cloud]
NIM --> AIE[NVIDIA AI Enterprise]
classDef hw fill:#fde68a,stroke:#92400e
classDef sw fill:#bbf7d0,stroke:#166534
classDef bf fill:#bfdbfe,stroke:#1e40af
classDef deploy fill:#fbcfe8,stroke:#9d174d
class HW,CUDA hw
class TE,MFSDP,MBR,DCP sw
class BF,HF bf
class VLLM,NIM,DGX,AIE,NEMO deploy
3.5 完整藥物發現端到端(從序列到候選分子)
flowchart LR
DB[(UniProt / NCBI
cell atlas / ChEMBL)] -->|bionemo-noodles
+ bionemo-scdl| Pre[Pre-training corpus]
Pre -->|ESM-2 / AMPLIFY pre-train| PLM[Protein LM]
Pre -->|Geneformer pre-train| sLM[Single-cell LM]
Pre -->|Evo2 pre-train| gLM[Genomic LM]
Target[(Disease target
e.g. KRAS G12D)] -->|Geneformer embed
+ scRNA-seq pathway| TgVal[Target validation]
PLM -->|fine-tune to predict
function / binding| TgVal
gLM -->|variant effect / essentiality| TgVal
TgVal --> Hit[Hit identification]
Hit -->|MoCo generative
DDPM / CFM / DFM| Cand[Candidate molecules]
Cand -->|ESMFold / OpenFold| Struct[Structure prediction]
Struct -->|docking / scoring
外部工具| Lead[Lead optimization]
Lead -->|BioNeMo NIM API| Pipeline[Production drug pipeline]
classDef db fill:#bfdbfe,stroke:#1e40af
classDef lm fill:#fef3c7,stroke:#92400e
classDef out fill:#dcfce7,stroke:#166534
class DB,Target db
class Pre,PLM,sLM,gLM,TgVal,Hit lm
class Cand,Struct,Lead,Pipeline out
3.6 三種 training stack 對比
| Recipe 命名 | training stack | 適合場景 | 代表 |
|---|---|---|---|
*_native_te | 原生 PyTorch + TE | 想看每行 train loop / 客製化 multi-GPU | esm2_native_te / llama3_native_te |
*_accelerate_te | HuggingFace Accelerate + TE | 想用 HF Trainer 邏輯 / accelerate config | esm2_accelerate_te |
*_megatron | Megatron-Bridge + Megatron-LM | 想 5D parallel / 跨 NVL36 / 上千 GPU | evo2_megatron / eden_megatron |
*_ptl_te | PyTorch Lightning + TE | 喜歡 Lightning API | codonfm_ptl_te |
*_mfsdp_fp8 | megatron-FSDP + FP8 | 中等規模、memory-efficient sharding | geneformer_native_te_mfsdp_fp8 |
⚠️ 同一個模型可能有多個 recipe(例如 ESM-2 有 esm2_native_te / esm2_accelerate_te / esm2_peft_te)— 依你的 training stack 熟悉度選,模型本身一樣。
4. Helper Scripts 詳細用法
4.1 train_ddp.py(每個 recipe 都有)— 訓練主入口
以 esm2_native_te/train_ddp.py 為例(9 KB):
1# 簡化版骨架
2import torch
3import torch.distributed as dist
4from transformer_engine.pytorch import fp8_autocast, Recipe
5from modeling_esm_te import NVEsmForMaskedLM
6from collator import MaskedLanguageModelCollator
7from dataset import ESM2Dataset
8
9def main():
10 # 1) 初始化 distributed
11 dist.init_process_group(backend="nccl")
12 local_rank = int(os.environ["LOCAL_RANK"])
13 torch.cuda.set_device(local_rank)
14
15 # 2) Load model + wrap DDP
16 config = NVEsmConfig.from_pretrained("nvidia/esm2_t33_650M_UR50D")
17 model = NVEsmForMaskedLM(config).cuda()
18 model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local_rank])
19
20 # 3) Data
21 train_ds = ESM2Dataset("train.parquet", tokenizer)
22 collator = MaskedLanguageModelCollator(tokenizer, mlm_probability=0.15)
23 loader = torch.utils.data.DataLoader(train_ds, batch_size=4, collate_fn=collator)
24
25 # 4) Optimizer + scheduler
26 optimizer = torch.optim.AdamW(model.parameters(), lr=4e-4)
27
28 # 5) FP8 autocast wrapper
29 fp8_recipe = Recipe(margin=0, fp8_format="HYBRID", amax_history_len=16)
30
31 # 6) Training loop
32 for step, batch in enumerate(loader):
33 batch = {k: v.cuda() for k, v in batch.items()}
34 with fp8_autocast(enabled=True, fp8_recipe=fp8_recipe):
35 outputs = model(**batch)
36 loss = outputs.loss
37 loss.backward()
38 optimizer.step()
39 optimizer.zero_grad()
啟動(單機 8 卡):
1torchrun --nproc_per_node=8 train_ddp.py
2# 或加 hydra override:
3torchrun --nproc_per_node=8 train_ddp.py train.batch_size=8 model.precision=fp8
啟動(slurm 多機):
1# 用 slurm.sh(recipe 內有範例)
2sbatch slurm.sh
4.2 train_fsdp2.py / train_mfsdp.py — 分片策略變體
| 檔案 | 用途 |
|---|---|
train_ddp.py | DDP(資料平行,模型完整 replica) |
train_fsdp2.py | PyTorch FSDP2(模型 sharded across GPUs) |
train_mfsdp.py | megatron-FSDP(NVIDIA 改進版,支援 5D parallel) |
train_ddp_cp.py | DDP + Context Parallel(長序列) |
train_fsdp2_cp.py | FSDP2 + Context Parallel |
選擇邏輯:
1模型 fit in 1 GPU? 是 → train_ddp.py
2 否 ↓
3模型 fit in 1 node (8 GPU)? 是 → train_fsdp2.py
4 否 ↓
5要 5D parallel / 跨 node? → train_mfsdp.py
6 ↓
7sequence 超長(>32K tokens)? → train_*_cp.py(加 context parallel)
4.3 convert.py — HF ↔ TE checkpoint 互轉
1# bionemo-recipes/models/esm2/convert.py
2from convert import convert_esm_hf_to_te, convert_esm_te_to_hf
3
4# HF format → TE format(要用本 framework 訓練時)
5convert_esm_hf_to_te(
6 hf_model_id="facebook/esm2_t33_650M_UR50D",
7 output_dir="./esm2-te-checkpoint",
8)
9
10# TE format → HF format(訓完要上 HF Hub / vLLM)
11convert_esm_te_to_hf(
12 te_checkpoint_dir="./checkpoints/final",
13 output_dir="./esm2-hf-export",
14)
為什麼需要:TE 用了 LayerNormLinear 等 fused layer,weight shape / naming 與標準 HF transformers 不同;convert 把 weight reshape + rename。
4.4 quantization.py — 低精度訓練
ESM-2 recipe 提供:
1# 三種精度路徑
2from quantization import (
3 setup_fp8_recipe, # H100+ supported
4 setup_mxfp8_recipe, # Blackwell only (SM 10.x)
5 setup_nvfp4_recipe, # NVFP4 — 最新格式
6)
7
8# 每層獨立控制(per-layer precision)
9recipe = setup_fp8_recipe(
10 margin=0,
11 fp8_format="HYBRID", # E4M3 forward, E5M2 backward
12 amax_history_len=16,
13 layers_to_skip=["embeddings"], # 嵌入層可保 BF16
14)
進階:fp4_debugging_stats.yaml / fp8_debugging_stats.yaml(recipe 內的 debugging tool 設定)讓你輸出每層 amax / scaling factor,用 fp8_analysis recipe 視覺化。
4.5 collator.py — sequence packing
核心優化:把多條短序列「打包」成一條長序列,配合 attention mask 避免跨序列互相 attend,可大幅提升 throughput。
1# bionemo-recipes/models/esm2/collator.py
2from collator import MaskedLanguageModelCollator
3
4collator = MaskedLanguageModelCollator(
5 tokenizer=tokenizer,
6 mlm_probability=0.15,
7 pad_to_multiple_of=128, # for TE FP8 alignment
8 sequence_packing=True, # ← 開這個
9 max_seq_length=8192,
10)
⚠️ pad_to_multiple_of 在 MFU 計算上會 inflate(issue #1561),算 useful work 時要扣回。
4.6 dataset.py — 資料介面
1# bionemo-recipes/recipes/esm2_native_te/dataset.py
2from dataset import ESM2Dataset
3
4ds = ESM2Dataset(
5 parquet_path="train.parquet", # recipe 附 1.9 MB 範例
6 tokenizer=tokenizer,
7 max_length=1024,
8)
9# 每筆是 {"input_ids": [...], "attention_mask": [...]}
4.7 checkpoint.py — DCP format
NVIDIA 用 **Distributed Checkpoint(DCP)**格式:每張 GPU 寫自己那一片,大模型不需要 gather 到單一 rank。
1from checkpoint import save_dcp, load_dcp
2
3# 儲存
4save_dcp(model, optimizer, scheduler, step=10000, save_dir="ckpt/step-10000")
5
6# 載入(任意 GPU 數都可,自動 reshard)
7load_dcp(model, optimizer, scheduler, save_dir="ckpt/step-10000")
4.8 bionemo-scdl — 單細胞 dataset
1from bionemo.scdl.io.single_cell_memmap_dataset import SingleCellMemMapDataset
2
3# 把 25K cell 的 h5ad → memory-mapped numpy
4data = SingleCellMemMapDataset(
5 "97e_scmm", # output dir
6 "97e96fb1-8caf-4f08-9174-27308eabd4ea.h5ad", # from CellxGene
7)
8
9# 用 AnnData 的人會習慣 .n_obs;本 API 改 function form
10print(data.number_of_rows()) # 等同 anndata.n_obs
11
12# 取一筆
13row = data[0] # 返回 sparse vector
為什麼快:memory-map 而非全量 load;ragged array 透過 paginated_load_cutoff / load_block_row_size 控制 chunk 大小。
4.9 bionemo-moco — 分子生成 interpolant
1from bionemo.moco.interpolants.continuous_time.discrete import D3PM
2from bionemo.moco.schedules.noise.continuous_noise_transforms import CosineSNRTransform
3
4# 設定一個 D3PM(Discrete Denoising Diffusion)
5d3pm = D3PM(
6 time_distribution=UniformTimeDistribution(),
7 prior_distribution=UniformPrior(num_classes=21), # 20 aa + 1 special
8 noise_schedule=DiscreteCosineNoiseSchedule(num_steps=1000),
9)
10
11# Training step
12x_t, t = d3pm.interpolate(x_0, t=t)
13loss = d3pm.loss(model(x_t, t), x_0, t)
14
15# Inference (denoise from prior)
16x_0_hat = d3pm.sample(model, num_steps=1000, batch_size=64)
支援 interpolant:DDPM / VDM / CFM / D3PM / MDLM / DFM。
4.10 bionemo-noodles — FASTA 高效 I/O
1from bionemo.noodles import FastaReader
2
3# 比 Biopython 快約 5–10x,用 Rust noodles backend
4with FastaReader("genome.fa") as reader:
5 for record in reader:
6 seq_id = record.id
7 seq = record.sequence
4.11 bionemo-size-aware-batching
1from bionemo.size_aware_batching.sampler import SizeAwareBatchSampler
2
3# 把長度近似的樣本放同一批,減少 padding 浪費
4sampler = SizeAwareBatchSampler(
5 dataset=dataset,
6 get_size=lambda x: len(x["input_ids"]),
7 max_total_size=8192, # 一批內 token 總數上限
8)
9loader = DataLoader(dataset, batch_sampler=sampler)
4.12 vllm_inference recipe
1cd bionemo-recipes/recipes/vllm_inference
2python infer.py --model nvidia/esm2_t33_650M_UR50D --sequences seqs.fa
vLLM 是 NVIDIA + UC Berkeley 主推的高效推論引擎;本 recipe 把 ESM-2 / AMPLIFY 等模型注入 vLLM 推論。
4.13 fp8_analysis recipe — FP8 訓練 debugger
1cd bionemo-recipes/recipes/fp8_analysis
2# 對訓練 log 中收集到的 amax history 做視覺化
3python analyze.py --log-dir ../esm2_native_te/logs --output heatmap.png
輸出 per-layer FP8 scaling heatmap,幫忙抓 underflow / overflow。
4.14 interpretability/sparse_autoencoders
1cd bionemo-recipes/interpretability/sparse_autoencoders
2# 用 SAE 解析 ESM2 / CodonFM 內部 feature
3uv pip install -e .
4python train_sae.py --backbone esm2 --layer 24 --num-features 32768
提供 interactive feature dashboard,類似 Anthropic 對 LLM 做 mech interp 的 biopharma 版本。
5. 應用場景:6 條 end-to-end pipeline
5.1 場景 A — Pre-train ESM-2 protein BERT(small scale 復現)
目標:在 8x H100 上 pretrain ESM-2 35M 200K steps(教學 / 概念驗證)。
1# Step 1: 進 container
2docker run --gpus=all --ipc=host --ulimit memlock=-1 -it \
3 nvcr.io/nvidia/clara/bionemo-framework:2.7 /bin/bash
4
5# Step 2: 進 recipe
6cd /workspace/bionemo-recipes/recipes/esm2_native_te
7
8# Step 3: 準備資料
9# README 提供 train.parquet 1.9MB(debug 用);正式跑要用 UniRef50
10# 或從 HF download:
11python -c "from datasets import load_dataset; load_dataset('agemagician/uniref50', split='train')"
12
13# Step 4: 啟動訓練(BF16 起手,先確認跑得動)
14torchrun --nproc_per_node=8 train_ddp.py \
15 model.precision=bf16 \
16 train.batch_size=16 \
17 train.lr=4e-4 \
18 train.max_steps=200000
19
20# Step 5: 切到 FP8(H100+)
21torchrun --nproc_per_node=8 train_ddp.py \
22 model.precision=fp8 \
23 model.fp8_format=HYBRID \
24 train.batch_size=24 # FP8 省記憶體,可開大 batch
25
26# Step 6: 訓完轉 HF format
27python -c "from convert import convert_esm_te_to_hf; convert_esm_te_to_hf('./ckpt/step-200000', './esm2-35M-hf')"
監控:
- Loss 曲線(wandb / tensorboard)
- MFU:用
perf_logger.py算(注意 issue #1561 修正) - FP8 amax:用
fp8_analysisrecipe 視覺化
5.2 場景 B — Fine-tune ESM-2 15B with LoRA(最常見場景)
目標:在自家 50K 蛋白序列上 fine-tune ESM-2 15B 做 contact prediction,受限於 GPU 數量用 LoRA。
1cd bionemo-recipes/recipes/esm2_peft_te
2
3# Step 1: 配置 LoRA
4cat > my_config.yaml <<EOF
5model:
6 base_model: nvidia/esm2_t48_15B_UR50D
7 precision: bf16 # LoRA 通常 BF16 即可
8lora:
9 r: 16
10 alpha: 32
11 target_modules: [query, key, value, dense]
12data:
13 train_file: my_proteins.parquet
14 max_length: 1024
15 packing: true # 開 sequence packing
16train:
17 batch_size: 2
18 grad_accum: 8
19 lr: 1e-4
20 max_steps: 5000
21EOF
22
23# Step 2: 訓
24torchrun --nproc_per_node=8 train.py --config my_config.yaml
25
26# Step 3: merge LoRA back
27python merge_lora.py --base nvidia/esm2_t48_15B_UR50D --lora ./lora_ckpt --output ./esm2-15B-merged
為什麼用 LoRA:15B model 全量 fine-tune 要 ≥ 32 GPU;LoRA 8 GPU 就能跑。
5.3 場景 C — Generative small molecule design(MoCo)
目標:訓練一個 conditional CFM(Conditional Flow Matching)生成 drug-like 分子。
1import torch
2from bionemo.moco.interpolants.continuous_time.continuous import CFM
3from bionemo.moco.schedules.inference_time_schedules import LinearInferenceSchedule
4
5# 1. 建立 CFM interpolant
6cfm = CFM(
7 sigma=0.1,
8 prior_distribution=GaussianPrior(),
9 time_distribution=UniformTimeDistribution(),
10)
11
12# 2. Training: 每 step 隨機 t,算 ground-truth velocity loss
13for batch in dataloader:
14 x_0 = batch["molecule_features"] # (B, N_atoms, D)
15 t = cfm.sample_time(x_0.size(0))
16 x_t = cfm.interpolate(x_0, t)
17 pred_velocity = model(x_t, t)
18 loss = cfm.loss(pred_velocity, x_0, x_t, t)
19 loss.backward()
20
21# 3. Sampling
22schedule = LinearInferenceSchedule(num_steps=100, time_start=0, time_end=1)
23x_0_hat = cfm.sample(model, schedule, batch_size=128, prior_shape=(50, 64))
⚠️ MoCo 只負責 interpolant;你要自己提供 model(U-Net / GNN 等)+ training loop。
5.4 場景 D — scRNA-seq foundation model(Geneformer)
目標:在自家 100M cell scRNA-seq 上 pretrain custom Geneformer。
1from bionemo.scdl.io.single_cell_memmap_dataset import SingleCellMemMapDataset
2import torch
3
4# 1. 把 50 個 h5ad 檔合成一個 memory-mapped dataset
5data = SingleCellMemMapDataset(
6 output_dir="combined_scmm",
7 input_files=["batch1.h5ad", "batch2.h5ad", ...],
8 paginated_load_cutoff=500, # MB
9 load_block_row_size=10000,
10)
11print(f"Total cells: {data.number_of_rows()}")
12
13# 2. 用 Geneformer recipe 訓
14# cd bionemo-recipes/recipes/geneformer_native_te_mfsdp_fp8
15# torchrun --nproc_per_node=8 train_mfsdp.py data.scmm_dir=combined_scmm
geneformer_native_te_mfsdp_fp8 同時用 mFSDP + FP8,記憶體效率最好。
5.5 場景 E — 基因體 SOTA Evo2(long-context)
目標:fine-tune Evo2 7B 做 variant effect prediction。
1cd bionemo-recipes/recipes/evo2_megatron
2
3# Build env(用 CI 腳本)
4./.ci_build.sh
5source ./.ci_test_env.sh
6
7# Preprocess FASTA → Megatron indexed binary
8preprocess_evo2 \
9 --input genome.fa \
10 --output-prefix /data/genome \
11 --json-keys sequence \
12 --vocab nucleotide
13
14# Fine-tune
15train_evo2 \
16 --config evo2_7b.yaml \
17 --data.path /data/genome \
18 --train.max_steps 10000
19
20# Inference
21infer_evo2 --model ckpt/final --prompt "ATCGATCG" --max-new-tokens 100
22
23# Predict log-likelihood on variants
24predict_evo2 --model ckpt/final --input variants.fa --output scores.tsv
特別:Evo2 是 Striped Hyena(SSM + attention),需要 warp-lang(README 已 pin <1.13.0)。Long context(1M+ nt)要用 context parallel。
5.6 場景 F — Sparse Autoencoder 解析 ESM2(mechanistic interpretability)
目標:找出 ESM-2 內部哪些 latent feature 對應 protein motif(α-helix / β-sheet / 活性中心)。
1cd bionemo-recipes/interpretability/sparse_autoencoders
2
3# Step 1: collect activations from ESM-2 layer 24
4python collect_activations.py \
5 --model nvidia/esm2_t33_650M_UR50D \
6 --layer 24 \
7 --sequences uniref50_sample.fa \
8 --output activations.h5
9
10# Step 2: train SAE
11python train_sae.py \
12 --activations activations.h5 \
13 --num-features 32768 \
14 --l1-coef 1e-3 \
15 --output sae_ckpt/
16
17# Step 3: 開 dashboard 看 feature dashboard
18python dashboard.py --sae sae_ckpt/ --port 8080
對應 NVIDIA Research 部落格:https://research.nvidia.com/labs/dbr/blog/sae/
6. 資安掃描報告
6.1 自動掃描指令
1cd /tmp/bionemo-framework
2grep -rn -E "eval\(|exec\(|os\.system|subprocess|shell=True|pickle\.load|__import__|input\(" \
3 --include="*.py" sub-packages/ bionemo-recipes/ 2>/dev/null | head -50
6.2 紅黃綠燈總結
1🟢 整體風險:低(research / training framework,本質不接外網)
2🟡 中度風險:3 項(subprocess 依賴 / shell drop_caches / pickle-like checkpoint)
3🔴 高度風險:0 項(無硬編碼密鑰 / 無 eval(user_input) / 無 SQL)
6.3 細項
| 風險等級 | 項目 | 位置 | 評估 |
|---|---|---|---|
| 🟢 | License | LICENSE/license.txt | Apache-2.0 |
| 🟢 | Secret detection | .gitleaks.toml + .gitleaksignore | 主動掃描 secret leak |
| 🟢 | Security policy | SECURITY.md | NVIDIA PSIRT 通報流程 |
| 🟢 | Code review | CODE-REVIEW.md + CODEOWNERS | 強制 review |
| 🟢 | nspect allowlist | .nspect-allowlist.toml | NVIDIA 內部安全掃描整合 |
| 🟢 | 模組界線 | tach.toml | 模組間 import 規則檢查 |
| 🟡 | subprocess 使用 | bionemo-scdl/simple-benchmark/scdl_speedtest.py:284,288 | 呼叫 du -s 算磁碟 size,有用 subprocess.run + 不開 shell=True → 低風險 |
| 🟡 | drop_caches sudo | bionemo-scspeedtest/benchmark.py:55 | benchmark 模式 sh -c "echo 3 > /proc/sys/vm/drop_caches" → 需要 root,只在 benchmark CLI 顯式呼叫,不是訓練主流程;但需注意:使用者跑此 benchmark 必須了解該 command 會清整個系統 page cache |
| 🟡 | input() 互動 | bionemo-scdl/simple-benchmark/scdl_speedtest.py:1317 | CLI 詢問「download example dataset? (y/N)」→ 標準互動,無 injection 風險 |
| 🟢 | pickle | (只在標準 PyTorch state_dict / DCP checkpoint) | 用 PyTorch 標準工具,無 untrusted pickle load |
| 🟢 | eval / exec | 無 hit | ✅ |
| 🟢 | 硬編碼密鑰 / token | 無 hit | ✅;HF_TOKEN 從環境變數讀 |
| 🟢 | 外網下載 | curl drive.google.com(Colab Quick Start 用 TE wheel mirror) | Google Drive mirror 是 NVIDIA 官方提供;正式建議改用 PyPI |
6.4 部署時要注意
| 情境 | 建議 |
|---|---|
| 內網 air-gapped 訓練 | 鎖 NGC container hash;TE wheel 走內部 PyPI mirror |
| 公司商用模型權重 | 個別審 NOML(Open Model License)vs Apache-2.0;ESM-2 上游有 CC-BY-NC |
| 客戶資料訓練 | 不要把 HF_TOKEN 或 wandb API key 寫進 config.yaml;用環境變數 |
| Benchmark 跑 drop_caches | 不要在 production 機器跑(會影響其他服務) |
6.5 NVIDIA 官方安全機制
- SECURITY.md:通報管道 https://www.nvidia.com/security
- .coderabbit.yaml:自動 PR review 整合
- CODEOWNERS:規定哪些 path 需要哪個 team review
- pre-commit-config.yaml:本地 commit 前自動掃 secret / lint
- .cursorrules / CLAUDE.md:AI agent 在這個 repo 內遵循的規則
7. FAQ
Q1: 我要 inference 不要訓練,需要本 repo 嗎?
不需要。直接從 HuggingFace 用 transformers 載入 NVIDIA 預訓練的 nvidia/esm2_* checkpoint 就好;或用 BioNeMo NIM API。本 repo 主要服務「我要客製化訓練」。
Q2: ESM-2 vs AMPLIFY 差在哪?
ESM-2 是 Meta 2022 經典 protein BERT(最大 15B);AMPLIFY 是 InstaDeep 2024 改良版(更小但表現相當)。框架都支援,建議新 project 先試 AMPLIFY(小、快、新)。
Q3: 我沒有 H100 / B200,可以用嗎?
可以但有侷限:
- A100:BF16 可訓練,無 FP8(A100 不支援 FP8 Transformer Engine 路徑)
- V100 / T4:只能跑小 model(< 1B),且要全 BF16 / FP16
- RTX 40 系列:可訓練小 model,FP8 支援度視具體型號(4090 有限)
Q4: 為什麼 recipe 重複實作這麼多 collator / dataset?
v2 設計刻意:每個 recipe self-contained,方便使用者只拉一個 folder 到 Colab 或自家環境。代價是程式碼重複 — NVIDIA 認為對 research 友善度勝過 DRY。
Q5: Evo2 為什麼放 evo2_megatron 不放 evo2_native_te?
Evo2 用 Striped Hyena(SSM + attention 混合),需要 Megatron-LM 的特殊 layer 與 5D parallel;用 native PyTorch 很難跨 NVL36 訓 40B。
Q6: 為什麼有 bionemo-scdl 不直接用 AnnData?
AnnData 把整份 dataset 載入 RAM,100M cell 直接爆;scdl 用 memory-mapped numpy,可以放硬碟讀。Issue #1577 / #1560 也在擴充功能(zarr / obsm)。
Q7: MoCo 跟 NVIDIA-Digital-Bio/MoFlow 是什麼關係?
MoFlow 是更早期 NVIDIA Digital Biology 出的 flow-based molecular generation;MoCo 是新的 modular 設計,統一介面包含所有 interpolant 家族(包含 flow / diffusion / discrete)。
Q8: Sparse Autoencoder for ESM2 跟 Anthropic 的 SAE 一樣嗎?
概念一樣(用 sparse coding 解析 latent feature),但 Anthropic 對 LLM 做、本 repo 對 protein LM 做。輸出的 feature 對應 protein motif / domain(如 α-helix 而非 noun phrase)。
Q9: bionemo-recipes 跟 NVIDIA/BioNeMo Blueprint 有什麼差?
- bionemo-framework(本 repo):程式碼 + 訓練 recipe(self-contained)
- NVIDIA/BioNeMo(hub):Blueprint + cookbook(產業 use-case 級別組裝,例如「target identification end-to-end pipeline」),最終呼叫的也是本 repo 的 recipe
類比:本 repo 是「鍋碗瓢盆 + 食材」;BioNeMo Blueprint 是「整套食譜書 + 配菜建議」。
Q10: 為什麼 README 中有 github.com/NVIDIA/bionemo-framework 又有 NVIDIA-BioNeMo/bionemo-framework?
GitHub 已從 NVIDIA/bionemo-framework 改 org 到 NVIDIA-BioNeMo/bionemo-framework(NVIDIA 把 BioNeMo 拉出獨立 org);舊 URL 仍 redirect。新文件統一用 NVIDIA-BioNeMo/。
Q11: 怎麼把訓完的 ESM-2 接到 vLLM?
1# 1. 用本 repo convert.py 把 TE checkpoint 轉成 HF format
2python -c "from convert import convert_esm_te_to_hf; convert_esm_te_to_hf('ckpt/', 'esm2-hf/')"
3
4# 2. 進 vllm_inference recipe
5cd bionemo-recipes/recipes/vllm_inference
6python infer.py --model ./esm2-hf --sequences my.fa
Q12: 我能不能不裝 NGC container 直接 pip install bionemo-scdl?
可以!sub-packages/* 設計就是獨立可裝。但 recipes 內的訓練腳本需要 TransformerEngine + Megatron-Bridge 等系統相依,強烈建議用 container。
8. 進階技巧
8.1 FP8 / MXFP8 / NVFP4 選擇策略
flowchart TD
A[要訓 ESM-2 / Llama-style model] --> B{硬體 SM 版本?}
B -->|< 9.0 V100/A100| BF16[只能 BF16/FP16]
B -->|9.0 H100| C{要極致省記憶體?}
C -->|否| FP8[FP8 HYBRID
最穩定]
C -->|是| FP8E[FP8 + sequence packing
+ activation checkpointing]
B -->|10.x Blackwell| D{model size?}
D -->|< 10B| MXFP8[MXFP8 試試
需要 amax tuning]
D -->|> 10B 規模化| NVFP4[NVFP4 最省
per-layer precision 控制]
8.2 Sequence Packing 加速分析
| Without packing | With packing |
|---|---|
| batch = 16 × seq_max 1024 = 16K token | 16K token 同樣,但每條序列實際長度不同 |
| padding waste 30–50% | padding waste < 5% |
| MFU 30–40% | MFU 50–65% |
注意 issue #1561:pad_to_multiple_of=128 的對齊 padding 在 MFU 算式中會被誤算為「useful work」,需用 actual_token_count 而非 padded_token_count。
8.3 mFSDP vs FSDP2 vs DDP 何時用
| 條件 | 選擇 |
|---|---|
| 模型 < GPU 記憶體 | DDP(最簡單) |
| 模型 > 單卡,但 ≤ 8 卡 | FSDP2(PyTorch 原生,廣泛測試) |
| 跨 node 大模型 + 想用 NVIDIA fork 優化 | mFSDP(megatron-FSDP,5D parallel 友善) |
| 超長 context(> 32K nt) | *_cp variant(context parallel) |
8.4 在 SLURM cluster 跑
1# bionemo-recipes/recipes/esm2_native_te/slurm.sh 範例
2#!/bin/bash
3#SBATCH --nodes=4
4#SBATCH --gres=gpu:8
5#SBATCH --ntasks-per-node=1
6#SBATCH --cpus-per-task=128
7
8srun --container-image=nvcr.io/nvidia/clara/bionemo-framework:2.7 \
9 --container-mounts=$PWD:/workspace \
10 bash -c "torchrun --nproc_per_node=8 \
11 --nnodes=$SLURM_NNODES \
12 --node_rank=$SLURM_NODEID \
13 --master_addr=$MASTER_ADDR \
14 train_mfsdp.py"
8.5 用 tach.toml 維持模組界線
1# 安裝 tach(模組依賴檢查工具)
2pip install tach
3
4# 檢查(CI 內建)
5tach check
tach.toml 規定例如 bionemo-scdl 不可以 import bionemo-moco,防止 cross-domain coupling。
8.6 NVFP4 per-layer precision
1# 在 quantization.py 內
2recipe = setup_nvfp4_recipe(
3 layers_to_skip_quant=["embeddings", "lm_head"], # 保 BF16
4 middle_layer_format="nvfp4", # 中間層用 NVFP4
5)
ESM-2 NVFP4 + MXFP8 mixed precision 在 B300 達 2,367 TFLOPS/GPU(README 提及)。
8.7 自家蛋白序列 → fine-tune workflow
1# 1. 把蛋白 csv 轉 parquet
2import pandas as pd
3df = pd.read_csv("my_proteins.csv") # columns: id, sequence
4df.to_parquet("my_proteins.parquet")
5
6# 2. 用 ESM-2 PEFT recipe
7# config.yaml 改 data.train_file: my_proteins.parquet
8.8 Megatron-Bridge 進階
Evo2 用 Megatron-Bridge 做 checkpoint 互轉:
1# NeMo2 ckpt → MBridge DCP
2evo2_convert_nemo2_to_mbridge --input nemo_ckpt/ --output mbridge_ckpt/
3
4# Savanna ckpt → MBridge DCP(社群 Striped Hyena 格式)
5evo2_convert_savanna_to_mbridge --input savanna_ckpt/ --output mbridge_ckpt/
6
7# MBridge → Vortex(純 PyTorch inference)
8evo2_export_mbridge_to_vortex --input mbridge_ckpt/ --output vortex.pt
8.9 整合 Weights & Biases
每個 recipe train_*.py 預設不裝 wandb;加:
1import wandb
2wandb.init(project="esm2-ft", config=cfg)
3# ... 在 training loop:
4wandb.log({"loss": loss.item(), "step": step, "lr": scheduler.get_last_lr()[0]})
或直接設 WANDB_API_KEY 環境變數,由 bionemo-recipeutils[basecamp] 自動接管(basecamp extra 含 wandb / mlflow / tensorboard)。
8.10 對 v1 codebase 的遷移建議
如果你還在 BioNeMo v1(基於 NeMo + PTL):
| v1 | v2 |
|---|---|
nemo.collections.nlp.models.esm2 | bionemo-recipes/models/esm2/modeling_esm_te.py |
nemo.collections.nlp.data.esm2_dataset | bionemo-recipes/recipes/esm2_*/dataset.py |
pytorch_lightning.Trainer | train_ddp.py / train_fsdp2.py 內手寫 loop(or codonfm_ptl_te 保留 PTL) |
OmegaConf YAML | 仍用 YAML(hydra_config/) |
建議:新 project 一律 v2;v1 codebase 維持但不要新功能投資。
9. 整合進其他工作流
9.1 整合進 AI knowledge template(本系統)
| Layer | 用途 |
|---|---|
| ai-gh-save | 已產生 inbox/2026-06-02-github-NVIDIA-BioNeMo-bionemo-framework.md |
| gh-tutorial-qd | 本詳細教學 md + qd + plain HTML(本流程) |
| paper-search | 找 Evo2 / CodonFM / ESM-2 原始 paper;找 Striped Hyena / SSM 相關 |
| paper-qa-lite | 把 ESM-2 + Evo2 + AMPLIFY tech reports 餵成 corpus,問「FP8 對 protein LM 訓練的影響」 |
| graphify | 對 bionemo-recipes/ 跑 graphify,看 model ↔ recipe ↔ collator 依賴 |
| kami | 把 §5 的 6 條 pipeline 抽成單頁 cheat sheet |
| research-pipeline-v2 | 用 BioNeMo recipe 設計研究 pipeline,套 9-stage 工作流 |
| tu-plan-generator | ChEMBL ID / SMILES 進來 → 走 drug-repurposing lens,引用 ESM-2 embedding 做 target embedding |
9.2 與 NVIDIA AI 全家桶整合
1 本 repo(bionemo-framework)
2 │
3 ┌─────────────────────┼─────────────────────┐
4 ▼ ▼ ▼
5 上游依賴 同層 NVIDIA repos 下游消費
6 │ │ │
7TransformerEngine NVIDIA/BioNeMo BioNeMo NIM
8Megatron-Bridge digital-biology- vLLM / TRT-LLM
9megatron-FSDP examples NVIDIA NGC
10NVIDIA-NeMo/Automodel NVIDIA-NeMo/ NVIDIA AI
11 Nemotron(共底層) Enterprise
9.3 與既有 NVIDIA 教學交互閱讀建議
| 你已讀 | 建議補讀 |
|---|---|
2026-06-02-tutorial-Nemotron.md | 本教學 §3.4 / §3.6(看 LLM stack 怎麼移到 biopharma) |
2026-06-02-tutorial-Megatron-Bridge.md | 本教學 §5.5 Evo2 流程 + §8.8 |
2026-06-02-tutorial-Automodel.md | 本教學 §3.6(Accelerate vs Megatron vs native 三種 stack) |
2026-06-02-tutorial-Cosmos.md | 比較 world model(Cosmos)vs domain LM(本 repo)的訓練 stack |
2026-06-02-NVlabs-explorer-guide.md | 本 repo 不在 NVlabs,但 SAE 來自 NVIDIA Research |
9.4 內部 biopharma 團隊 onboarding
新人路徑(4 週):
- Week 1:跑
esm2_native_teQuick Start(Colab 即可);理解 TE FP8 概念 - Week 2:跑
esm2_peft_teLoRA fine-tune 自家小資料;學會convert.py - Week 3:選方向 — (a)
geneformer_*單細胞、(b)evo2_megatron基因體、(c)bionemo-moco分子生成 - Week 4:讀 SECURITY.md + CODE-REVIEW.md + tach.toml;開始 PR
9.5 LLMOps / MLOps pipeline 整合
1[資料層] CellxGene / UniRef / ChEMBL → S3 / GCS
2 │
3[預處理] bionemo-scdl / bionemo-noodles → memory-mapped shards
4 │
5[訓練] bionemo-recipes → DCP checkpoint
6 │
7[Registry] HuggingFace Hub / MLflow Model Registry
8 │
9[部署] BioNeMo NIM / vLLM / TRT-LLM
10 │
11[監控] Prometheus + Grafana + drift detection
可用工具:Argo Workflows / Airflow / Kubeflow / NVIDIA NeMo-Run 編排。
9.6 與 Claude Code / Cursor / Codex 整合
repo 內含 CLAUDE.md + .cursorrules,已內建 AI agent 規則。直接從 repo root 啟動 Claude Code / Cursor 即可載入。
10. 重點摘要 Checklist
10.1 概念與架構
- 能解釋 bionemo-framework 在 NVIDIA Clara BioPharma 中的「引擎」角色
- 能說出與 NVIDIA/BioNeMo(Blueprint hub)的關係(引擎 vs 資產目錄)
- 能解釋與 NVIDIA-NeMo/Nemotron 的共同底層(Megatron-Bridge / TransformerEngine)
- 能說出 bionemo-recipes/ 與 sub-packages/ 的設計分工
- 能說出三種 training stack(native PyTorch / Accelerate / Megatron)何時用
10.2 模型與 recipe
- 能列出 ESM-2 / AMPLIFY / Geneformer / Evo2 / CodonFM 的領域定位
- 能說出 MoCo 包含哪些 interpolant(DDPM / VDM / CFM / D3PM / MDLM / DFM)
- 知道
*_native_te/*_accelerate_te/*_megatron/*_ptl_te的差異 - 知道 Mixtral / Qwen / Llama3 為什麼也在 biopharma framework
10.3 工具鏈
- 會用 NGC container 起手
- 會用 VSCode devcontainer
- 會用
convert.py做 HF ↔ TE checkpoint 互轉 - 會用
bionemo-scdl載入 h5ad - 會用
bionemo-noodles讀 FASTA - 會用
bionemo-moco寫 diffusion / flow
10.4 訓練優化
- 能解釋 FP8 / MXFP8 / NVFP4 何時用
- 知道 sequence packing 的優劣(含 MFU 算錯陷阱 #1561)
- 知道 DDP / FSDP2 / mFSDP / context parallel 的選擇
- 會用
fp8_analysisrecipe 視覺化 amax
10.5 部署與生產
- 會把訓完 checkpoint 上 HuggingFace
- 知道 BioNeMo NIM 部署路徑
- 會接 vLLM / TRT-LLM
- 知道 SLURM 多 node 啟動方法
10.6 倫理與合規
- 知道 repo LICENSE Apache-2.0 ≠ 模型權重 LICENSE(多為 NOML)
- 知道 ESM-2 上游 Meta 條款(CC-BY-NC,商用注意)
- 知道 LICENSE/third_party.txt 71.9K 含上百個上游條款
- 知道 SECURITY.md 通報流程
11. 進一步閱讀
11.1 官方資源
- 主文件:https://docs.nvidia.com/bionemo-framework/latest/
- GitHub Pages(nightly):https://nvidia-bionemo.github.io/bionemo-framework/
- NGC container:https://catalog.ngc.nvidia.com/orgs/nvidia/teams/clara/containers/bionemo-framework
- Brev.dev launchable:README 內 deploy button
- Clara BioPharma 主頁:https://www.nvidia.com/en-us/clara/biopharma/
11.2 模型 Hub
- NVIDIA BioNeMo HF collection:https://huggingface.co/collections/nvidia/bionemo-686d3faf75aa1edde8c118d9
- ESM-2 8M / 35M / 150M / 650M / 3B / 15B:
huggingface.co/nvidia/esm2_* - CodonFM preprint:https://research.nvidia.com/labs/dbr/assets/data/manuscripts/nv-codonfm-preprint.pdf
- SAE blog:https://research.nvidia.com/labs/dbr/blog/sae/
11.3 相關 NVIDIA repos
- NVIDIA/BioNeMo(Blueprint hub,與本 repo 互補)
- NVIDIA/digital-biology-examples(廣域生科範例)
- NVIDIA-NeMo/Megatron-Bridge(checkpoint bridge,evo2_megatron 直接用)
- NVIDIA-NeMo/Automodel(HF 加速橋接)
- NVIDIA-NeMo/Nemotron(LLM hub,共底層)
- NVIDIA/TransformerEngine(FP8/MXFP8/NVFP4 kernel 主體)
- NVIDIA/Megatron-LM(5D parallel 上游)
11.4 競品 / 對照組
- DeepMind AlphaFold 3(閉源結構預測)
- Meta ESM / ESMFold(開源蛋白 BERT,本 repo 加速版的上游)
- OpenFold / OpenFold3(社群結構預測)
- Boltz-1 / RoseTTAFold(社群結構預測)
- InstaDeep AMPLIFY(蛋白 BERT 的上游,已被本 repo 整合)
- Arc Institute Evo2 原始 repo(基因體 SSM 模型)
11.5 經典 paper
- ESM-2:Lin et al. 2022 (Science) — protein language model
- AMPLIFY:InstaDeep 2024 — smaller protein BERT
- Geneformer:Theodoris et al. 2023 (Nature) — single-cell foundation model
- Evo2:Arc Institute 2026 (Nature) — long-context genomic SSM
- Striped Hyena:Together AI / Stanford — SSM + attention hybrid
11.6 本系統內相關文件
inbox/2026-06-02-github-NVIDIA-BioNeMo-bionemo-framework.md(本 repo 的 gh-save 標準報告)inbox/2026-06-02-tutorial-Nemotron.md(共底層的 LLM hub 教學)inbox/2026-06-02-tutorial-Cosmos.md(物理 world model)inbox/2026-06-02-tutorial-Megatron-Bridge.md(evo2_megatron 依賴)inbox/2026-06-02-tutorial-Automodel.md(HF Accelerate 加速)inbox/2026-06-02-NVlabs-explorer-guide.md(NVIDIA Research 入口)
完成時間:2026-06-02 編譯路徑:
projects/bionemo-framework/quarkdown-out/02-tutorial/
Comments