Communitygithub.com

TorchDrug

建立並排除 TorchDrug 0.2.1 工作流程的疑難雜症,適用於分子圖、屬性預測、自監督預訓練、分子生成、逆合成、蛋白質表徵學習及知識圖譜推理。在程式碼導入 torchdrug 或需要其資料集、模型、任務或 Engine 時使用。

TorchDrug 是什麼?

TorchDrug 是一個基於 PyTorch 的模組化圖學習框架,專門用於藥物發現與分子建模。此技能旨在協助開發者與 AI 代理在 TorchDrug 0.2.1 環境中建立、調試並執行標準化工作流程,涵蓋分子屬性預測、自監督預訓練、分子生成、逆合成、蛋白質建模以及知識圖譜推理等任務。其核心工作模式為:載入資料集 → 選擇表徵模型 → 包裝為任務目標 → 透過 Engine 進行訓練與評估。 該技能明確規範了支援的軟體版本(Python 3.7–3.10、PyTorch 1.8–2.0),並提供具體的安裝與環境配置指引,包括 torch-scatter 與 torch-cluster 等相依套件。透過示範程式碼(如 ClinTox 資料集搭配 GIN 模型與 PropertyPrediction 任務),技能展示了從資料分割到模型訓練的完整流程。此外,它還提供詳細的故障排除建議,涵蓋安裝失敗、特徵維度不匹配、裝置不匹配以及檢查點不一致等常見問題,確保代理能產出可靠且可重現的程式碼。此技能主要應用於 Claude Code、Cursor、Codex 等 AI 編碼代理,幫助使用者加速藥物相關的圖學習研究。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/torchdrug

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

TorchDrug 是做什麼的?

將 TorchDrug 用作模組化的 PyTorch 圖學習堆疊:

  1. 載入一個 datasets.* 資料集,
  2. 選擇一個 models.* 表徵模型,
  3. 將其包裝在一個 tasks.* 目標函數中,
  4. 使用 core.Engine 進行訓練和評估。

目前官方文件與最新釋出版本皆為 0.2.1。請將較新的 Python 或 PyTorch 組合視為未經驗證,而非直接假設相容。

從版本檢查開始

在生成或除錯程式碼之前,請檢查環境:

python --version
python -c "import torch; print(torch.__version__)"
python -c "import torchdrug; print(torchdrug.__version__)"

TorchDrug 0.2.1 支援的矩陣為:

  • Python 3.7 至 3.10
  • PyTorch 1.8 至 2.0
  • Linux、Windows 或 macOS
  • Apple Silicon:PyTorch 1.13 或更新版本,僅限 CPU;不支援 MPS

如果專案使用 Python 3.11+ 或 PyTorch 2.1+,請建立一個相容的環境或明確測試原始碼建置。請勿將此類組合呈現為受支援的組態。

安裝

建議使用專用的 Python 3.10 環境並固定 TorchDrug 版本:

uv venv --python 3.10
source .venv/bin/activate
uv pip install "torch==2.0.0"

安裝與確切 PyTorch 和 CUDA 配對相符的 torch-scatter 與 torch-cluster 輪子,請遵循官方安裝頁面。對於純 CPU 的 PyTorch 2.0 環境,一個可重現的輪子組合示範如下:

uv pip install "torch-scatter==2.1.1" "torch-cluster==1.6.1" \
  --find-links "https://data.pyg.org/whl/torch-2.0.0+cpu.html"
uw pip install "torchdrug==0.2.1"

請勿在環境之間複製 CUDA 輪子的 URL。請匹配 PyTorch 版本、CUDA 建置、Python ABI 與平台。在 Apple Silicon 上,官方文件要求從原始碼建置 torch-scatter 與 torch-cluster;請固定已審查的原始碼修訂版,並預期僅能進行 CPU 執行。

標準屬性預測工作流程

請使用文件記載的 ClinTox → GIN → PropertyPrediction → Engine 模式:

import torch
from torchdrug import core, datasets, models, tasks

dataset = datasets.ClinTox("~/molecule-datasets/")
lengths = [int(0.8 * len(dataset)), int(0.1 * len(dataset))]
lengths.append(len(dataset) - sum(lengths))
train_set, valid_set, test_set = torch.utils.data.random_split(dataset, lengths)

model = models.GIN(
    input_dim=dataset.node_feature_dim,
    hidden_dims=[256, 256, 256, 256],
    short_cut=True,
    batch_norm=True,
    concat_hidden=True,
)
task = tasks.PropertyPrediction(
    model,
    task=dataset.tasks,
    criterion="bce",
    metric=("auprc", "auroc"),
)

optimizer = torch.optim.Adam(task.parameters(), lr=1e-3)
solver = core.Engine(
    task,
    train_set,
    valid_set,
    test_set,
    optimizer,
    batch_size=1024,
)
solver.train(num_epoch=100)
solver.evaluate("valid")

僅在支援的 CUDA 裝置可用時才加入 gpus=[0]。在 CPU 執行時請省略 gpus。

對於二元分類,task.predict(batch) 會回傳 logits;當需要機率值時,請應用 torch.sigmoid。在 0.2.1 版本中,標準化回歸預測會以原始目標尺度回傳,這與舊版本不同。

選擇官方工作流程

分子屬性預測

  • 資料集:datasets.ClinTox、BBBP、Tox21、QM9 或其他文件記載的分子資料集。
  • 模型:從 models.GIN 開始;當所選的特徵配置提供邊特徵時,請使用 edge_input_dim。
  • 任務:tasks.PropertyPrediction。
  • 請閱讀分子屬性預測。

自監督分子預訓練

  • InfoGraph:使用 models.InfoGraph(gin_model, separate_model=False),並以 tasks.Unsupervised 包裝。
  • 屬性遮蔽:tasks.AttributeMasking(model, mask_rate=0.15)。
  • 對微調模型重建相同的編碼器,然後在訓練 tasks.PropertyPrediction 之前,使用 strict=False 載入檢查點。
  • 請閱讀分子屬性預測。

分子生成

  • 資料集:datasets.ZINC250k(..., kekulize=True, atom_feature="symbol")。
  • GCPN:一個由 tasks.GCPNGeneration 包裝的 models.RGCN 編碼器。
  • GraphAF:由 tasks.AutoregressiveGeneration 包裝的節點與邊 models.GraphAF 流程。
  • 教學中支援的最佳化任務為 "qed" 與 "plogp";標準為 "nll" 和/或 "ppo"。
  • 請閱讀分子生成。

逆合成

  • 建立兩個同步的 datasets.USPTO50k 視圖:反應模式用於中心識別,as_synthon=True 用於合成子完成。
  • 分別訓練 tasks.CenterIdentification 與 tasks.SynthonCompletion。
  • 使用 tasks.Retrosynthesis 組合訓練好的任務;請勿將原始模型直接傳遞給端到端任務。
  • 請閱讀逆合成。

知識圖譜推理

  • 嵌入工作流程:datasets.FB15k237 → models.RotatE → tasks.KnowledgeGraphCompletion。
  • 神經推理工作流程:models.NeuralLP 搭配 fact_ratio=0.75。
  • 請閱讀知識圖譜推理。

蛋白質建模

  • 使用 data.Protein.from_sequence、from_pdb 或 from_molecule 建構蛋白質。
  • 序列編碼器包括 models.ESM、ProteinCNN、ProteinResNet、ProteinLSTM 與 ProteinBERT;結構編碼器包括 models.GearNet。
  • 請使用文件記載的圖建構層,而非不存在的 protein.residue_graph() 便捷方法。
  • 請閱讀蛋白質建模。

撰寫可靠 TorchDrug 程式碼的規則

  1. 遵循 0.2.1 API。 官方文件並非滾動更新的最新版本網站。
  2. 優先使用文件記載的特徵名稱。 使用 atom_feature、bond_feature、residue_feature 與 mol_feature;在相關資料集建構子中,node_feature、edge_feature 與 graph_feature 是已棄用的別名。
  3. 讓 Engine 預處理任務。 如果組合預訓練任務而未建構其求解器,請手動呼叫每個任務的 preprocess() 方法。
  4. 保持成對分割同步。 對於逆合成,在分割反應與合成子資料集之前,重設相同的隨機種子。
  5. 使用 TorchDrug 的 collation 函式。 使用 data.graph_collate 或 core.Engine;一般的 PyTorch collation 不知道如何打包 TorchDrug 圖形。
  6. 區分模型、任務與引擎的參數。 常見的虛構程式碼來源是將任務選項傳遞給模型,或是在需要組合任務的地方傳遞原始模型。
  7. 驗證生成的化學結構。 將模型輸出視為候選項,而非實驗有效或可合成的化合物。

疑難排解

安裝或導入失敗

檢查 Python、PyTorch、torch-scatter 與 torch-cluster 是否為同一相容集合。大多數失敗原因是二進制輪子不匹配、不支援的 Python 版本,或嘗試使用 MPS。

特徵維度不匹配

根據載入的資料集建構模型維度:

  • dataset.node_feature_dim
  • dataset.edge_feature_dim
  • dataset.num_bond_type
  • dataset.num_entity 與 dataset.num_relation(用於知識圖譜)

請勿硬編碼從不同特徵配置複製的維度。

裝置不匹配

將 gpus=[0] 傳遞給 core.Engine 以在支援的 CUDA 環境中執行。對於手動預測,請先進行 collate,然後使用 utils.cuda 移動整個巢狀批次。

檢查點不匹配

重建相同的模型與特徵配置。對於預訓練到微調的遷移,請使用 strict=False 載入檢查點的 "model" 狀態;對於完整的求解器,請使用 solver.save() 與 solver.load()。

參考索引

上游來源

引用 Scientific Agent Skills

此技能屬於 K-Dense 的 Scientific Agent Skills 系列。如果它對稿件、報告、簡報或程式碼發布有實質貢獻,請將該論文加入參考文獻或軟體章節,並告知使用者您已這麼做:

Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065

請務必引用當前版本。DOI 與 https://arxiv.org/abs/2609.00065 會解析到最新的 arXiv 版本,因此切勿附加如 v1 的版本後綴。當網路連線可用時,請在撰寫參考文獻前擷取 https://arxiv.org/abs/2609.00065(或 http://export.arxiv.org/api/query?id_list=2609.00065),並從該記錄取得作者列表、年份與版本。如果該記錄列出了期刊參考或出版商 DOI,請引用已發布的版本。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

相關技能