cell2sentence (C2S / C2S-Scale) — 完整教學
把單細胞 RNA-seq 表達矩陣轉成 LLM 看得懂的「cell sentence (細胞句子)」,用大型語言模型做 cell type prediction (細胞類型預測)、cell generation (細胞生成)、perturbation response prediction (擾動反應預測) 等任務。
1. 專案定位
Cell2Sentence (C2S) 是 Yale University van Dijk Lab 於 2024 年提出的 single-cell + LLM 整合框架。最核心的創新是一個極簡的資料表徵轉換:
expression vector → rank-ordered gene name string (cell sentence)
舉例:一個細胞的基因表達向量 {GAPDH: 12.4, ACTB: 9.1, RPL13: 7.2, ...} 在 rank-transform 後變成:
1GAPDH ACTB RPL13 EEF1A1 RPS27 ...
這個字串可以直接餵給任何 LLM tokenizer,意味著:
- 不需要為單細胞資料設計專屬 architecture(如 scGPT 的 attention mask)
- 可以直接 reuse pretrained LLM(Pythia / Gemma)並做 SFT (Supervised Fine-Tuning; 監督微調)
- 可以用自然語言 prompt 描述任務、組合多任務
最新版本:C2S-Scale 把模型放大到 27B 參數(基於 Gemma-2),並把 transcriptomics (轉錄體) 與 textual data (文字資料) 統一在同個模型空間。
為何重要
| 傳統 single-cell ML | Cell2Sentence |
|---|---|
| 專用 architecture(scGPT / scBERT / Geneformer) | 直接 reuse LLM |
| 必須重訓專屬 tokenizer / embedding | 用 LLM 既有 tokenizer |
| 多任務需設計多 head | 用 prompt template 切換任務 |
| 模型最大 ~600M 參數 | C2S-Scale 達 27B |
| 難以加入自然語言 metadata | 自然支援(tissue name / abstract / cell type) |
2. 安裝指南
環境需求
- Python 3.8+
- PyTorch(GPU 強烈建議,27B 模型需多 GPU)
- HuggingFace
transformers/datasets/accelerate scanpy/anndatafor single-cell I/O
標準安裝(pip)
1pip install cell2sentence==1.2.0
Conda 安裝(含開發環境)
1git clone https://github.com/vandijklab/cell2sentence.git
2cd cell2sentence
3conda create -n cell2sentence python=3.8
4conda activate cell2sentence
5make install # 內部呼叫 python -m pip install -e .
選配:Flash Attention(加速長序列推論)
1pip install flash-attn --no-build-isolation
教學筆記本 #5(cell generation)有開啟 flash-attention 2 的範例。
3. 核心架構解析
C2S 套件的核心模組分為 5 個 Python 檔(共約 1465 行 code),對應 4 個概念層級:
flowchart LR
subgraph Input["輸入層 (scanpy / anndata)"]
A1["AnnData
表達矩陣
(cells × genes)"]
end
subgraph Transform["轉換層 (utils.py)"]
T1["generate_vocabulary
建立 gene vocab"]
T2["generate_sentences
rank → 字串"]
T3["build_arrow_dataset
HF Dataset 封裝"]
end
subgraph Wrap["封裝層 (csdata + csmodel)"]
W1["CSData
資料包裝"]
W2["CSModel
模型包裝"]
end
subgraph Tasks["任務層 (tasks.py + prompt_formatter.py)"]
K1["PromptFormatter
任務 prompt 組合"]
K2["generate_cells
predict_cell_types
embed_cells"]
end
A1 --> T1 --> T2 --> T3 --> W1
W1 --> K1
W2 --> K1
K1 --> K2
K2 --> Output["輸出:
cell sentences /
cell type labels /
embeddings"]
核心模組職責
| 檔案 | 行數 | 主要 class / function | 職責 |
|---|---|---|---|
csdata.py | 180 | CSData | 包裝 Arrow / HuggingFace Dataset,提供 vocabulary 管理與 train/test split |
csmodel.py | 337 | CSModel | 包裝 AutoTokenizer + AutoModelForCausalLM,提供 fine-tune / inference 介面 |
tasks.py | 203 | generate_cells_conditioned_on_cell_type / predict_cell_types_of_data / embed_cells | end-user 任務 API(最常用) |
prompt_formatter.py | 253 | PromptFormatter / C2SPromptFormatter / C2SMultiCellPromptFormatter | 把 cell sentence + task metadata 組合成 LLM prompt |
utils.py | 486 | generate_vocabulary / generate_sentences / tokenize_all / reconstruct_expression_from_cell_sentence | 底層轉換、tokenization、逆轉換 |
資料流(典型 fine-tuning workflow)
sequenceDiagram
participant U as User
participant SC as scanpy/AnnData
participant CSD as CSData
participant PF as PromptFormatter
participant CSM as CSModel
participant HF as HuggingFace Trainer
U->>SC: load adata
U->>CSD: generate_vocabulary(adata)
U->>CSD: generate_sentences(adata, vocab)
CSD-->>U: Arrow Dataset (cell_sentence column)
U->>PF: format prompts for "cell_type_prediction"
PF-->>U: tokenized HF Dataset
U->>CSM: load pretrained "C2S-Pythia-410m"
U->>HF: Trainer(model=csm, dataset=...)
HF-->>U: fine-tuned model
U->>CSM: predict_cell_types_of_data(test_adata)
CSM-->>U: 預測 cell type 字串
支援任務(SUPPORTED_TASKS)
從 prompt_formatter.py 取出的官方支援任務清單:
單細胞 (single-cell):
cell_type_prediction— 預測單細胞 cell typecell_type_generation— 條件式生成(給定 cell type 生成 cell sentence)
多細胞 (multi-cell):
tissue_prediction— 預測組織類型tissue_conditional_generation— 給定 tissue 生成多細胞 samplenatural_language_interpretation— 用自然語言詮釋多細胞 cluster
4. 11 個官方 Tutorial 筆記本詳解
| # | 檔名 | 功能 |
|---|---|---|
| 0 | c2s_tutorial_0_data_preparation.ipynb | 用免疫組織資料示範資料載入與前處理 |
| 1 | c2s_tutorial_1_rank_transformation_and_reconstruction.ipynb | C2S 核心:expression → cell sentence → expression 的雙向轉換 |
| 2 | c2s_tutorial_2_cell_embedding.ipynb | 用 C2S 模型取得 cell type embeddings |
| 3 | c2s_tutorial_3_finetuning_on_new_datasets.ipynb | 在自己的 scRNA dataset 上 fine-tune |
| 4 | c2s_tutorial_4_cell_type_prediction.ipynb | cell type prediction 流程 |
| 5 | c2s_tutorial_5_cell_generation.ipynb | 條件式 cell generation(含 flash-attention 2 設定) |
| 6 | c2s_tutorial_6_cell_annotation_with_foundation_model.ipynb | 用 foundation model 做 cell type annotation |
| 7 | c2s_tutorial_7_custom_prompt_templates.ipynb | 自訂 prompt template,搭配自己的 SFT 資料 |
| 8 | c2s_tutorial_8_multi_cell_tissue_prediction.ipynb | multi-cell tissue prediction |
| 9 | c2s_tutorial_9_natural_language_interpretation.ipynb | multi-cell cluster 的自然語言詮釋 |
| 10 | c2s_tutorial_10_perturbation_response_prediction.ipynb | 擾動反應預測 — C2S-Scale 最新任務 |
建議閱讀順序:0 → 1 → 2 → 4 → 3 → 5 → 7 → 8 → 9 → 10
5. 應用場景
5.1 學術研究
| 情境 | 推薦模型 | tutorial |
|---|---|---|
| 想做 cell type prediction 跑跨 dataset 評估 | C2S-Pythia-410M cell type prediction | #4 |
| 想用 C2S 嵌入做下游 clustering / 視覺化 | 任一 C2S model + embed_cells | #2 |
| 在自己 scRNA dataset 做 SFT | 410M (參數較小可單卡) 或 1B (多卡) | #3 + #7 |
| 預測 drug perturbation 的轉錄反應 | C2S-Scale Gemma 2B / 27B | #10 |
| 多細胞 tissue-level prediction | diverse multi-cell model | #8 |
| 用 LLM 解釋 single-cell cluster 的生物意義 | Gemma C2S-Scale | #9 |
5.2 產業 / 製藥
- 靶點發現 (target discovery):用
perturbation_response_prediction預測 KO / drug 在罕見 cell type 的轉錄反應 → 縮短濕實驗 cycle - biomarker generation:條件式 cell generation 模擬「典型疾病細胞」做 silico assay
- dataset summarization:自然語言摘要單細胞 atlas,加速 IND-enabling 資料整理
5.3 在地化生科應用(台灣場景)
- 結合 GTEx 台灣亞群或 BIOBANK 資料微調 C2S 做台灣特有族群的單細胞表徵
- 用 C2S-Scale Gemma + 中文 prompt 詮釋 cluster,整合進病理報告草稿產生流程
6. 資安掃描報告
對 src/ 做 OWASP-style 靜態掃描,重點關注:subprocess 執行、shell injection、不安全反序列化、外部網路請求、secret 寫死。
| 風險類別 | 命中 | 等級 |
|---|---|---|
subprocess.run / call / Popen | 0 | 🟢 |
os.system | 0 | 🟢 |
shell=True | 0 | 🟢 |
eval() / exec() | 0 | 🟢 |
pickle.loads (untrusted) | 0 | 🟢 |
pickle.dump (生產 split indices) | 1(csmodel.py:198) | 🟢 自有寫入,無反序列化風險 |
requests / urllib 外部呼叫 | 0 | 🟢 |
curl / wget shell call | 0 | 🟢 |
| 硬編碼 API key / token / password | 0 | 🟢 |
HuggingFace tokenizer 內部 pad_token / eos_token | N/A | 🟢 非機密 token |
結論:🟢 整體低風險
cell2sentence 是個純粹的 ML library,沒有任何 shell exec / 外部網路請求 / 反序列化 untrusted data 的路徑。模型下載走 HuggingFace from_pretrained(標準受信任管道),資料載入走 anndata / scanpy 既有路徑。
使用建議
| 項目 | 建議 |
|---|---|
| 在公司內網部署 | 從 HuggingFace mirror 下載模型,pin 版本 |
| 自家 fine-tuning checkpoint 流通 | safetensors 格式優先;避免 .bin / .pt 帶 pickle 風險 |
| 自製 prompt template | 注意 tokenize_all 不截斷使用者輸入;長序列要設 max_num_tokens |
| 跑公開 demo | 限制 max_eval_samples(預設 500)避免長 inference DoS |
7. FAQ
Q1:為什麼不直接用 scGPT 或 Geneformer?
A:scGPT / Geneformer 需要重訓專屬 architecture 和 tokenizer。C2S 直接用 LLM tokenizer,搭便車最新 LLM scaling laws + alignment 技術(SFT / RLHF / DPO),且可以原生整合自然語言 metadata。
Q2:rank-ordering 會不會丟失定量訊息?
A:會丟失絕對表達量,但保留相對排序。團隊在原 ICML 2024 paper 證明,對 cell type prediction / cell generation 等任務,相對排序的訊息量足夠;且模型可從大量 cell 中學到「典型表達 pattern」。
Q3:fine-tune C2S-Pythia-410M 需要多少 GPU?
A:依 tutorial #3,single A100 80GB 可訓練 batch_size=4。記憶體瓶頸主要在 sequence length(cell sentence 通常 1024–2048 tokens)。可用 LoRA / QLoRA 降到 24 GB 卡。
Q4:可以用 C2S 處理 spatial transcriptomics 嗎?
A:repo 目前沒有 spatial-specific tutorial,但 multi-cell prompting (#8) 框架可以直接擴展:把 spatial 鄰近細胞當作 “multi-cell context”,prompt 內加 spatial coords 字串。
Q5:擾動預測(#10)的訓練資料從哪來?
A:以公開 Perturb-seq dataset(如 Replogle 2022, Norman 2019)為主,C2S-Scale 在 CellxGene 預訓練後 fine-tune。詳見 c2s_tutorial_10_perturbation_response_prediction.ipynb。
Q6:為何 issue tracker 有不少 perturbation 與 fine-tune 問題未解?
A:C2S-Scale 是 2025 年 4 月才公開的新模型,社群還在驗證 reproducibility(issue #13、#15、#18、#23)。建議參考 paper supplementary + tutorial #10 + 直接聯絡 van Dijk Lab。
Q7:商業使用授權?
A:code 在 2025-10-31 從原本的 BY-NC-ND 改為 Apache 2.0(commit d9869a3),但模型本身在 HuggingFace 上的授權需個別檢查(部分模型基於 Gemma-2,要遵守 Gemma terms)。
8. 進階技巧
8.1 自訂 prompt template
prompt_formatter.py 的 C2SPromptFormatter 是 abstract base,子類化它可以做:
1from cell2sentence.prompt_formatter import C2SPromptFormatter
2
3class MyClinicalPromptFormatter(C2SPromptFormatter):
4 def format_prompt(self, cell_sentence, metadata):
5 return (
6 f"Patient: {metadata['patient_id']}\n"
7 f"Tissue: {metadata['tissue']}\n"
8 f"Cells (top genes by expression):\n{cell_sentence}\n"
9 f"Predict disease state:"
10 )
教學 #7 有完整範例。注意:自訂 template 後 tokenizer 的 max_length 要重新校正。
8.2 推論加速
| 技巧 | 加速比 | 適用 |
|---|---|---|
| flash-attention 2 | 2–4× | 長序列 (>512 tokens) |
torch.compile (PyTorch 2.0+) | 1.3–1.8× | 推論固定 batch_size |
| INT8 / INT4 quantization (bitsandbytes) | 1.5–3× | 記憶體不足時優先 |
| Speculative decoding | 1.5–2× | C2S-Scale-1B → 27B 對搭 |
8.3 與 scanpy pipeline 整合
1import scanpy as sc
2from cell2sentence.csdata import CSData
3from cell2sentence.tasks import embed_cells
4
5adata = sc.read_h5ad("my_data.h5ad")
6sc.pp.normalize_total(adata)
7sc.pp.log1p(adata)
8sc.pp.highly_variable_genes(adata, n_top_genes=2000)
9adata = adata[:, adata.var.highly_variable]
10
11# C2S embeddings 可直接灌回 adata.obsm
12embeddings = embed_cells(csmodel, adata)
13adata.obsm["X_c2s"] = embeddings
14sc.pp.neighbors(adata, use_rep="X_c2s")
15sc.tl.umap(adata)
8.4 fine-tune 上自己的 dataset
1from cell2sentence.csdata import CSData
2from cell2sentence.csmodel import CSModel
3
4# 1. 準備資料
5csdata = CSData.from_anndata(adata, vocab_path="vocab.json")
6ds = csdata.to_hf_dataset() # Arrow Dataset
7
8# 2. 載入 base model
9csmodel = CSModel.from_pretrained("vandijklab/C2S-Pythia-410m-cell-type-prediction")
10
11# 3. fine-tune
12csmodel.train(
13 dataset=ds,
14 task="cell_type_prediction",
15 epochs=3,
16 learning_rate=5e-5,
17 output_dir="./my_c2s_model"
18)
9. 整合進其他工作流
9.1 結合 paper-search 做文獻回顧
1paper: cell2sentence single-cell LLM perturbation prediction year=2024-2026 n=15
搜索 A+B+C 類別(生醫 + 預印本 + 跨領域 AI),整理 SOTA 比較。
9.2 用 ai-notebooklm 做主題深讀
把 C2S + scGPT + Geneformer 三篇 paper 一起丟進同個 notebooklm,提問「三者的 architectural trade-offs」。
9.3 結合 patent-creator 評估專利潛力
若內部團隊計畫做 C2S 衍生方法,可走 patent-creator 工作流。注意:repo 在 2025-11-04 已 removed patent.md,原本的 patent notice 已撤下,但 BY-NC-ND → Apache 2.0 的授權轉移仍需評估。
9.4 用 graphify 建立子領域 knowledge map
1graphify update /config/workspace/.../inbox/Life science/
把 cell2sentence 跟其他 single-cell LLM 專案(scGPT、Geneformer、scFoundation)的關係視覺化。
10. 重點摘要 Checklist
- ✅ 概念:rank-ordering 把 expression → cell sentence string,讓 LLM 原生處理 scRNA-seq
- ✅ 架構:5 模組(csdata / csmodel / tasks / prompt_formatter / utils),共 ~1465 行 Python
- ✅ 模型:Pythia 160M/410M/1B + Gemma 2B/27B,全在 HuggingFace
- ✅ 任務:cell type prediction / cell generation / embedding / perturbation / tissue / NL interpretation
- ✅ 資料規模:57M+ human/mouse cells from CellxGene + HCA
- ✅ 資安:🟢 低風險(無 shell exec / 外部網路 / untrusted pickle)
- ✅ 授權:Apache 2.0(code,2025-10-31 起);模型授權依 HuggingFace card
- ✅ 教學:11 個 Jupyter notebooks,從 data prep 到 perturbation prediction 全覆蓋
11. 進一步閱讀
官方資源
- 主 paper:Scaling LLMs for Next-Generation Single-Cell Analysis (bioRxiv 2025)
- 前身 paper:Cell2Sentence (ICML 2024)
- 文件:https://vandijklab-cell2sentence.readthedocs.io/
- Google Research blog:Teaching machines the language of biology
- HuggingFace collection:vandijklab/cell2sentence-models
對照閱讀
- scGPT (Cui 2024 Nature Methods) — 專用 transformer + tokenizer
- Geneformer (Theodoris 2023 Nature) — 30M cell pretraining, gene rank-based
- scFoundation (Hao 2023) — 100M cell foundation model
- scBERT (Yang 2022) — BERT 風格 single-cell encoder
Comments