Views
No views yet
from_pretrained() and save_pretrained() interface1cd GeneMamba_HuggingFace
2pip install -e .pip install genemamba-hfpip install -r requirements.txt1import torch
2import numpy as np
3from transformers import AutoTokenizer, AutoModel
4
5# Load pretrained model and tokenizer
6tokenizer = AutoTokenizer.from_pretrained(
7 "mineself2016/GeneMamba",
8 trust_remote_code=True
9)
10model = AutoModel.from_pretrained(
11 "mineself2016/GeneMamba",
12 trust_remote_code=True
13)
14
15# Prepare input: ranked gene sequences
16# Shape: (batch_size, seq_len) with gene Ensembl IDs as token IDs
17batch_size, seq_len = 8, 2048
18input_ids = torch.randint(2, 25426, (batch_size, seq_len))
19
20# Extract cell embedding
21outputs = model(input_ids)
22cell_embeddings = outputs.pooled_embedding # shape: (8, 512)
23
24print(f"Cell embeddings shape: {cell_embeddings.shape}")
25# Output: Cell embeddings shape: torch.Size([8, 512])outputs.pooled_embedding for downstream tasksconfig.embedding_pooling)ENSG00000000003)1import torch
2from transformers import AutoModelForSequenceClassification, Trainer, TrainingArguments
3from torch.utils.data import Dataset
4
5# Load model with classification head
6model = AutoModelForSequenceClassification.from_pretrained(
7 "mineself2016/GeneMamba",
8 num_labels=10, # number of cell types
9 trust_remote_code=True
10)
11
12# Prepare dataset
13class GeneExpressionDataset(Dataset):
14 def __init__(self, input_ids, labels):
15 self.input_ids = input_ids
16 self.labels = labels
17
18 def __len__(self):
19 return len(self.input_ids)
20
21 def __getitem__(self, idx):
22 return {
23 "input_ids": self.input_ids[idx],
24 "labels": self.labels[idx]
25 }
26
27# Example data
28X_train = torch.randint(2, 25426, (1000, 2048))
29y_train = torch.randint(0, 10, (1000,))
30
31train_dataset = GeneExpressionDataset(X_train, y_train)
32
33# Fine-tune with Trainer
34trainer = Trainer(
35 model=model,
36 args=TrainingArguments(
37 output_dir="./results",
38 num_train_epochs=5,
39 per_device_train_batch_size=32,
40 learning_rate=2e-5,
41 save_strategy="epoch",
42 ),
43 train_dataset=train_dataset,
44)
45
46trainer.train()num_labels=2num_labels=NBCEWithLogitsLoss in custom training loop1import torch
2from pathlib import Path
3from transformers import AutoTokenizer, AutoConfig, AutoModelForMaskedLM, Trainer, TrainingArguments
4from transformers.trainer_utils import get_last_checkpoint
5
6tokenizer = AutoTokenizer.from_pretrained(
7 "mineself2016/GeneMamba",
8 trust_remote_code=True,
9)
10
11print("vocab_size:", tokenizer.vocab_size) # 25426
12print("unk/pad:", tokenizer.unk_token_id, tokenizer.pad_token_id) # 0, 1
13print("cls/mask:", tokenizer.cls_token_id, tokenizer.mask_token_id) # None, None
14
15# Build model config (no local modeling file import required)
16config = AutoConfig.from_pretrained("mineself2016/GeneMamba", trust_remote_code=True)
17config.vocab_size = 25426
18config.hidden_size = 512
19config.num_hidden_layers = 24
20config.max_position_embeddings = 2048
21config.mamba_mode = "mean"
22
23# Resume if checkpoint exists
24output_dir = "./from_scratch_pretrain"
25checkpoint_dir = Path(output_dir) / "checkpoint-last"
26
27if checkpoint_dir.exists():
28 resume_from_checkpoint = str(checkpoint_dir)
29else:
30 resume_from_checkpoint = get_last_checkpoint(output_dir)
31
32if resume_from_checkpoint is not None:
33 model = AutoModelForMaskedLM.from_pretrained(
34 resume_from_checkpoint,
35 trust_remote_code=True,
36 local_files_only=True,
37 )
38else:
39 model = AutoModelForMaskedLM.from_config(config, trust_remote_code=True)
40
41class NextTokenTrainer(Trainer):
42 def compute_loss(self, model, inputs, return_outputs=False):
43 input_ids = inputs["input_ids"]
44 logits = model(input_ids=input_ids).logits
45 shift_logits = logits[:, :-1, :].contiguous()
46 shift_labels = input_ids[:, 1:].contiguous().to(shift_logits.device)
47 loss = torch.nn.functional.cross_entropy(
48 shift_logits.view(-1, shift_logits.size(-1)),
49 shift_labels.view(-1),
50 )
51 return loss
52
53trainer = NextTokenTrainer(
54 model=model,
55 args=TrainingArguments(
56 output_dir=output_dir,
57 num_train_epochs=3,
58 per_device_train_batch_size=32,
59 learning_rate=2e-5,
60 ),
61 train_dataset=train_dataset,
62)
63
64trainer.train(resume_from_checkpoint=resume_from_checkpoint)| Model Name | Layers | Hidden Size | Parameters | Download |
|---|---|---|---|---|
GeneMamba-24l-512d | 24 | 512 | ~170M | 🤗 Hub |
GeneMamba-24l-768d | 24 | 768 | ~380M | 🤗 Hub |
GeneMamba-48l-512d | 48 | 512 | ~340M | 🤗 Hub |
GeneMamba-48l-768d | 48 | 768 | ~750M | 🤗 Hub |
GeneMambaModel (Backbone)
├── Embedding Layer (vocab_size × hidden_size)
├── MambaMixer (Bidirectional SSM processing)
│ ├── EncoderLayer 0
│ ├── EncoderLayer 1
│ ├── ...
│ └── EncoderLayer N-1
├── RMSNorm (Layer Normalization)
└── Output: Pooled Embedding (batch_size × hidden_size)
Task-Specific Heads:
├── GeneMambaForSequenceClassification
│ └── Linear(hidden_size → num_labels)
├── GeneMambaForMaskedLM
│ └── Linear(hidden_size → vocab_size)ENSG00000000003)1import numpy as np
2import scanpy as sc
3
4# Load scRNA-seq data
5adata = sc.read_h5ad("data.h5ad")
6
7# For each cell, rank genes by expression
8gene_ids = []
9for cell_idx in range(adata.n_obs):
10 expression = adata.X[cell_idx].toarray().flatten()
11 ranked_indices = np.argsort(-expression) # Descending order
12 ranked_gene_ids = [gene_id_mapping[idx] for idx in ranked_indices[:2048]]
13 gene_ids.append(ranked_gene_ids)
14
15# Convert to token IDs
16input_ids = tokenizer(gene_ids, return_tensors="pt", padding=True)["input_ids"]examples/ directory for complete scripts:1_extract_embeddings.py - Extract cell embeddings2_finetune_classification.py - Cell type annotation3_pretrain_from_scratch.py - Train from scratch (next-token + optional resume)1@article{qi2025genemamba,
2 title={GeneMamba: An Efficient and Effective Foundation Model on Single Cell Data},
3 author={Qi, Cong and Fang, Hanzhang and Jiang, Siqi and Song, Xun and Hu, Tianxing and Zhi, Wei},
4 journal={arXiv preprint arXiv:2504.16956},
5 year={2026}
6}trust_remote_code=True Errortrust_remote_code=True (safe if loading from official repo)sys.path.insert(0, '.') if loading local code1from transformers import AutoModel
2model = AutoModel.from_pretrained(
3 "mineself2016/GeneMamba",
4 trust_remote_code=True,
5 force_download=True,
6)rm -rf ~/.cache/huggingface/hub/models--mineself2016--GeneMamba1args = TrainingArguments(
2 per_device_train_batch_size=8, # Reduce from 32
3 ...
4)GeneMamba_repo/
├── config.json
├── model.safetensors
├── tokenizer.json ← Required
├── tokenizer_config.json ← Required
└── ...