Skip to main content

A comprehensive toolkit for fine-tuning and inference with DNA Language Models

Project description

DNALLM - DNA Large Language Model Toolkit

DNALLM Logo

Python 3.11+ License: MIT PyPI version

DNALLM is a comprehensive, open-source toolkit designed for fine-tuning and inference with DNA Language Models. It provides a unified interface for working with various DNA sequence models, supporting tasks ranging from basic sequence classification to advanced in-silico mutagenesis analysis. With built-in Model Context Protocol (MCP) support, DNALLM enables seamless communication with traditional large language models, allowing for enhanced integration and interoperability in AI-powered DNA analysis workflows.

๐Ÿš€ Key Features

  • ๐Ÿ”„ Model Management: Load and switch between 150+ pre-trained DNA language models from Hugging Face and ModelScope
  • ๐ŸŽฏ Multi-Task Support: Binary/multi-class classification, regression, NER, MLM, and generation tasks
  • ๐Ÿ“Š Benchmarking: Multi-model performance comparison and evaluation metrics
  • ๐Ÿ”ง Fine-tuning: Comprehensive training pipeline with configurable parameters
  • ๐Ÿ“ฑ Interactive Interfaces: Jupyter notebooks and Marimo-based interactive demos
  • ๐ŸŒ MCP Support: Model Context Protocol for server/client deployment with real-time streaming
  • ๐Ÿงฌ Advanced Analysis: In-silico mutagenesis, saturation mutation analysis, and mutation effect visualization
  • ๐Ÿงช Comprehensive Testing: 200+ test cases covering all major functionality

๐Ÿงฌ Supported Models

DNALLM supports a wide range of DNA language models including:

Masked Language Models (MLM)

  • DNABERT Series: Plant DNABERT, DNABERT, DNABERT-2, DNABERT-S
  • Caduceus Series: Caduceus-Ph, Caduceus-PS, PlantCaduceus
  • Specialized Models: AgroNT, GENA-LM, GPN, GROVER, MutBERT, ProkBERT

Causal Language Models (CLM)

  • EVO Series: EVO-1, EVO-2
  • Plant Models: Plant DNAGemma, Plant DNAGPT, Plant DNAMamba
  • Other Models: GENERator, GenomeOcean, HyenaDNA, Jamba-DNA, Mistral-DNA

Model Sources

  • Hugging Face Hub: Primary model repository
  • ModelScope: Alternative model source with additional models
  • Custom Models: Support for locally trained or custom architectures

๐Ÿ› ๏ธ Installation

Prerequisites

  • Python 3.11 or higher (recommended)
  • Git
  • CUDA-compatible GPU (optional, for GPU acceleration)
  • Environment Manager: Choose one of the following:
    • Python venv (built-in)
    • Conda/Miniconda (recommended for scientific computing)

Quick Installation with uv (Recommended)

DNALLM uses uv for dependency management and packaging.

What is uv is a fast Python package manager that is 10-100x faster than traditional tools like pip.

Method 1: Using venv + uv

# Clone repository
git clone https://github.com/zhangtaolab/DNALLM.git
cd DNALLM

# Create virtual environment
python -m venv .venv

# Activate virtual environment
source .venv/bin/activate  # Linux/MacOS
# or
.venv\Scripts\activate     # Windows

# Upgrade pip (recommended)
pip install --upgrade pip

# Install uv in virtual environment
pip install uv

# Install DNALLM with base dependencies
uv pip install -e '.[base]'

# For MCP server support (optional)
uv pip install -e '.[mcp]'

# Verify installation
python -c "import dnallm; print('DNALLM installed successfully!')"

Method 2: Using conda + uv

# Clone repository
git clone https://github.com/zhangtaolab/DNALLM.git
cd DNALLM

# Create conda environment
conda create -n dnallm python=3.12 -y

# Activate conda environment
conda activate dnallm

# Install uv in conda environment
conda install uv -c conda-forge

# Install DNALLM with base dependencies
uv pip install -e '.[base]'

# For MCP server support (optional)
uv pip install -e '.[mcp]'

# Verify installation
python -c "import dnallm; print('DNALLM installed successfully!')"

GPU Support

For GPU acceleration, install the appropriate CUDA version:

# For venv users: activate virtual environment
source .venv/bin/activate  # Linux/MacOS
# or
.venv\Scripts\activate     # Windows

# For conda users: activate conda environment
# conda activate dnallm

# CUDA 12.4 (recommended for recent GPUs)
uv pip install -e '.[cuda124]'

# Other supported versions: cpu, cuda121, cuda126, cuda128
# Nvidia 5090 Please use cuda128 & torch==2.7
uv pip install -e '.[cuda128]'

Native Mamba Support

Native Mamba architecture runs significantly faster than transformer-compatible Mamba architecture, but native Mamba depends on Nvidia GPUs.

If you need native Mamba architecture support, after installing DNALLM dependencies, use the following command:

# For venv users: activate virtual environment
source .venv/bin/activate  # Linux/MacOS

# For conda users: activate conda environment
# conda activate dnallm

# Ensure CUDA path is set correctly (nvcc version must match your PyTorch CUDA version)
export PATH=/usr/local/cuda-12/bin:$PATH
nvcc -V  # Verify CUDA compiler version

# Install Mamba support
uv pip install -e '.[mamba]' --no-cache-dir --no-build-isolation --link-mode=copy

# If encounter network issue, using the special install script for mamba (optional)
sh scripts/install_mamba.sh  # select github proxy

Note: The nvcc version must match your PyTorch CUDA version. For example, if you installed PyTorch with CUDA 12.8, you need nvcc from CUDA 12.x. Mismatched versions will cause build failures.

Please ensure your machine can connect to GitHub, otherwise Mamba dependencies may fail to download.

Note that Plant DNAMamba, Caduceus, PlantCaduceus, PlantCAD2, Jamba-DNA, JanusDNA models are all based on Mamba architecture. Therefore, the training and inference of these models can be accelerated by installing the native mamba support.

Install Dependencies for Special Models

Several models require extra dependencies to train or inference.

These models are listed below:

Models Model Type Source Dependencies
EVO-1 CausalLM Hugging Face GitHub
EVO2 CausalLM Hugging Face GitHub
GPN MaskedLM Hugging Face GitHub
megaDNA CausalLM Hugging Face GitHub
LucaOne CausalLM Hugging Face GitHub
Omni-DNA CausalLM Hugging Face GitHub

The installation method for the dependencies of these models can be found here.

๐Ÿš€ Quick Start

1. Basic Model Loading and Inference

from dnallm import load_config, load_model_and_tokenizer, DNAInference

# Load configuration
configs = load_config("./example/notebooks/inference/inference_config.yaml")

# Load model and tokenizer
model_name = "zhangtaolab/plant-dnagpt-BPE-promoter_strength_protoplast"
model, tokenizer = load_model_and_tokenizer(
    model_name, 
    task_config=configs['task'], 
    source="huggingface"
)

# Initialize inference engine
inference_engine = DNAInference(config=configs, model=model, tokenizer=tokenizer)

# Make inference
sequence = "AATATATTTAATCGGTGTATAATTTCTGTGAAGATCCTCGATACTTCATATAAGAGATTTTGAGAGAGAGAGAGAACCAATTTTCGAATGGGTGAGTTGGCAAAGTATTCACTTTTCAGAACATAATTGGGAAACTAGTCACTTTACTATTCAAAATTTGCAAAGTAGTC"
inference_result = inference_engine.infer(sequence)
print(f"Inference result: {inference_result}")

2. In-silico Mutagenesis Analysis

from dnallm import Mutagenesis

# Initialize mutagenesis analyzer
mutagenesis = Mutagenesis(config=configs, model=model, tokenizer=tokenizer)

# Generate saturation mutations
mutagenesis.mutate_sequence(sequence, replace_mut=True)

# Evaluate mutation effects
predictions = mutagenesis.evaluate(strategy="mean")

# Visualize results
plot = mutagenesis.plot(predictions, save_path="mutation_effects.pdf")

3. Model Fine-tuning

from dnallm.datahandling import DNADataset
from dnallm.finetune import DNATrainer

# Prepare dataset
dataset = DNADataset(
    data_path="path/to/your/data.csv",
    task_type="binary_classification",
    text_column="sequence",
    label_column="label"
)

# Initialize trainer
trainer = DNATrainer(
    config=configs,
    model=model,
    tokenizer=tokenizer,
    train_dataset=dataset
)

# Start training
trainer.train()

4. MCP Server Deployment

# Start MCP server for real-time DNA sequence prediction
from dnallm.mcp import DNALLMMCPServer

# Initialize MCP server
server = DNALLMMCPServer("config/mcp_server_config.yaml")
await server.initialize()

# Start server with SSE transport for real-time streaming
server.start_server(host="0.0.0.0", port=8000, transport="sse")

MCP Server Features

  • Real-time Streaming: Server-Sent Events (SSE) for live prediction updates
  • Multiple Transport Protocols: STDIO, SSE, and Streamable HTTP
  • Comprehensive Tools: 10+ MCP tools for DNA sequence analysis
  • Model Management: Dynamic model loading and switching
  • Batch Processing: Efficient handling of multiple sequences
  • Health Monitoring: Built-in server diagnostics and status checks

Available MCP Tools

  • dna_sequence_predict - Single sequence prediction
  • dna_batch_predict - Batch sequence processing
  • dna_multi_model_predict - Multi-model comparison
  • dna_stream_predict - Real-time streaming prediction
  • list_loaded_models - Model management
  • health_check - Server monitoring

๐Ÿ“š Examples and Tutorials

Interactive Demos (Marimo)

# Launch Jupyter Lab
uv run jupyter lab

# Fine-tuning demo
uv run marimo run example/marimo/finetune/finetune_demo.py

# Inference demo
uv run marimo run example/marimo/inference/inference_demo.py

# Benchmark demo
uv run marimo run example/marimo/benchmark/benchmark_demo.py

Web-based UI (Gradio)

# Launch Gradio configuration generator app
uv run python ui/run_config_app.py

# Or run the model config generator directly
uv run python ui/model_config_generator_app.py

Jupyter Notebooks

# Launch Jupyter Lab
uv run jupyter lab

# Available notebooks:
# - example/notebooks/finetune_binary/ - Binary classification fine-tuning
# - example/notebooks/finetune_multi_labels/ - Multi-label classification
# - example/notebooks/finetune_NER_task/ - Named Entity Recognition
# - example/notebooks/inference/ - Model inference
# - example/notebooks/in_silico_mutagenesis/ - Mutation analysis
# - example/notebooks/inference_for_tRNA/ - tRNA-specific analysis
# - example/notebooks/generation_evo_models/ - EVO model inference
# - example/notebooks/lora_finetune_inference/ - LoRA fine-tuning
# - example/notebooks/embedding_attention.ipynb - Embedding and attention analysis
# - example/notebooks/finetune_custom_head/ - Custom classification head
# - example/notebooks/finetune_generation/ - Sequence generation
# - example/notebooks/generation/ - Sequence generation examples
# - example/notebooks/generation_megaDNA/ - MegaDNA model inference
# - example/notebooks/interpretation/ - Model interpretation
# - example/notebooks/data_prepare/ - Data preparation examples
# - example/notebooks/benchmark/ - Model evaluation and benchmarking

๐Ÿ—๏ธ Project Structure

DNALLM/
โ”œโ”€โ”€ dnallm/                  # Core library package
โ”‚   โ”œโ”€โ”€ cli/                 # Command-line interface
โ”‚   โ”œโ”€โ”€ configuration/       # Configuration management
โ”‚   โ”œโ”€โ”€ datahandling/        # Dataset processing
โ”‚   โ”œโ”€โ”€ finetune/            # Fine-tuning pipeline
โ”‚   โ”œโ”€โ”€ inference/           # Inference & analysis tools
โ”‚   โ”œโ”€โ”€ models/              # Model loading & registry
โ”‚   โ”œโ”€โ”€ tasks/               # Task definitions & metrics
โ”‚   โ”œโ”€โ”€ utils/               # Utility functions
โ”‚   โ””โ”€โ”€ mcp/                 # MCP server implementation
โ”œโ”€โ”€ cli/                     # Legacy CLI scripts (deprecated)
โ”œโ”€โ”€ example/                 # Examples & tutorials
โ”‚   โ”œโ”€โ”€ marimo/              # Interactive Marimo apps
โ”‚   โ””โ”€โ”€ notebooks/           # Jupyter notebooks
โ”œโ”€โ”€ docs/                    # Documentation
โ”œโ”€โ”€ tests/                   # Test suite
โ”œโ”€โ”€ ui/                      # Gradio web interfaces
โ”œโ”€โ”€ scripts/                 # Development scripts
โ”œโ”€โ”€ .github/                 # GitHub workflows
โ”œโ”€โ”€ pyproject.toml           # Project configuration
โ””โ”€โ”€ README.md                # This file

๐Ÿ”ง Command Line Interface

DNALLM provides convenient CLI tools:

# Main CLI with subcommands
dnallm --help

# Training
dnallm train --config path/to/config.yaml
# or
dnallm-train --config path/to/config.yaml

# Inference
dnallm inference --config path/to/config.yaml --input path/to/sequences.txt
# or
dnallm-inference --config path/to/config.yaml --input path/to/sequences.txt

# Model configuration generator
dnallm-model-config-generator

# MCP server
dnallm-mcp-server --config path/to/config.yaml

๐ŸŽฏ Supported Task Types

DNALLM supports the following task types:

  • EMBEDDING: Extract embeddings, attention maps, and token probabilities for downstream analysis
  • MASK: Masked language modeling task for pre-training
  • GENERATION: Text generation task for causal language models
  • BINARY: Binary classification task with two possible labels
  • MULTICLASS: Multi-class classification task that specifies which class the input belongs to (more than two)
  • MULTILABEL: Multi-label classification task with multiple binary labels per sample
  • REGRESSION: Regression task which returns a continuous score
  • NER: Token classification task which is usually for Named Entity Recognition

๐Ÿงช Testing

DNALLM includes a comprehensive test suite with 200+ test cases:

# Run all tests
uv run pytest

# Run specific test categories
uv run pytest tests/inference/ -v
uv run pytest tests/mcp/ -v
uv run pytest tests/tasks/ -v

# Run with coverage
uv run pytest --cov=dnallm --cov-report=html

๐Ÿ“– Documentation

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details on:

  • Code style and standards
  • Testing requirements
  • Pull request process
  • Development setup

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • Hugging Face - Model hosting and transformers library
  • ModelScope - Alternative model repository

๐Ÿ“ž Support


DNALLM - Empowering DNA sequence analysis with state-of-the-art language models.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dnallm-0.3.0.tar.gz (273.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dnallm-0.3.0-py3-none-any.whl (360.1 kB view details)

Uploaded Python 3

File details

Details for the file dnallm-0.3.0.tar.gz.

File metadata

  • Download URL: dnallm-0.3.0.tar.gz
  • Upload date:
  • Size: 273.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for dnallm-0.3.0.tar.gz
Algorithm Hash digest
SHA256 96b97cbbffd1378f97d1df0eb228aa42b8193aa56f0649262cb3bda8c2d7e249
MD5 5e6a702a59a431db44414050e9c29406
BLAKE2b-256 bc9b1311bb7234cdfc0cc508ff8758c256723dcf13cc65437c97cea494fbc362

See more details on using hashes here.

File details

Details for the file dnallm-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: dnallm-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 360.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for dnallm-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 19402ecb33b0f187846d16fb21f2d2ed15f0b79c1355575ebc9ad93ecb048ea0
MD5 ef38f8bb1ca715635065129dfc7cde17
BLAKE2b-256 d0fe188445ddc4258894b9f86e30eec6437a96c13f3a7d98b8f1ce04d8c252a2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page