Instructions to use mineself2016/GeneMamba with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use mineself2016/GeneMamba with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="mineself2016/GeneMamba", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("mineself2016/GeneMamba", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Remove stale file: examples/01_extract_embeddings.py
Browse files
examples/01_extract_embeddings.py
DELETED
|
@@ -1,150 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Phase 1: Extract Cell Embeddings
|
| 3 |
-
Demonstrates how to load GeneMamba and extract cell embeddings for downstream analysis.
|
| 4 |
-
|
| 5 |
-
Usage:
|
| 6 |
-
python examples/1_extract_embeddings.py
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
import torch
|
| 10 |
-
import numpy as np
|
| 11 |
-
from transformers import AutoTokenizer, AutoModel
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
def main():
|
| 15 |
-
print("=" * 80)
|
| 16 |
-
print("GeneMamba Phase 1: Extract Cell Embeddings")
|
| 17 |
-
print("=" * 80)
|
| 18 |
-
|
| 19 |
-
# ============================================================
|
| 20 |
-
# Step 1: Load pretrained model and tokenizer
|
| 21 |
-
# ============================================================
|
| 22 |
-
print("\n[Step 1] Loading model and tokenizer...")
|
| 23 |
-
|
| 24 |
-
# For this example, we use a local model path
|
| 25 |
-
# In practice, you would use: "username/GeneMamba-24l-512d"
|
| 26 |
-
model_name = "GeneMamba-24l-512d" # Change to HF Hub path when available
|
| 27 |
-
|
| 28 |
-
try:
|
| 29 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
| 30 |
-
model_name,
|
| 31 |
-
trust_remote_code=True,
|
| 32 |
-
local_files_only=True # Try local first
|
| 33 |
-
)
|
| 34 |
-
model = AutoModel.from_pretrained(
|
| 35 |
-
model_name,
|
| 36 |
-
trust_remote_code=True,
|
| 37 |
-
local_files_only=True
|
| 38 |
-
)
|
| 39 |
-
except Exception as e:
|
| 40 |
-
print(f"Note: Could not load from '{model_name}': {e}")
|
| 41 |
-
print("Using mock data for demonstration...")
|
| 42 |
-
|
| 43 |
-
# For demonstration without actual checkpoint
|
| 44 |
-
from configuration_genemamba import GeneMambaConfig
|
| 45 |
-
from modeling_genemamba import GeneMambaModel
|
| 46 |
-
|
| 47 |
-
config = GeneMambaConfig(
|
| 48 |
-
vocab_size=25426,
|
| 49 |
-
hidden_size=512,
|
| 50 |
-
num_hidden_layers=24,
|
| 51 |
-
embedding_pooling="mean",
|
| 52 |
-
)
|
| 53 |
-
model = GeneMambaModel(config)
|
| 54 |
-
tokenizer = None
|
| 55 |
-
|
| 56 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 57 |
-
model = model.to(device)
|
| 58 |
-
model.eval()
|
| 59 |
-
|
| 60 |
-
print(f"✓ Model loaded on device: {device}")
|
| 61 |
-
print(f"✓ Model config: hidden_size={model.config.hidden_size}, "
|
| 62 |
-
f"num_layers={model.config.num_hidden_layers}")
|
| 63 |
-
|
| 64 |
-
# ============================================================
|
| 65 |
-
# Step 2: Prepare simulated single-cell data
|
| 66 |
-
# ============================================================
|
| 67 |
-
print("\n[Step 2] Preparing sample data...")
|
| 68 |
-
|
| 69 |
-
batch_size = 8
|
| 70 |
-
seq_len = 2048
|
| 71 |
-
vocab_size = 25426
|
| 72 |
-
|
| 73 |
-
# Simulate ranked gene sequences
|
| 74 |
-
# In practice, this would come from your scRNA-seq data
|
| 75 |
-
# Genes should be ranked by expression (highest first)
|
| 76 |
-
input_ids = torch.randint(2, vocab_size, (batch_size, seq_len)).to(device)
|
| 77 |
-
|
| 78 |
-
print(f"✓ Created sample input:")
|
| 79 |
-
print(f" - Batch size: {batch_size}")
|
| 80 |
-
print(f" - Sequence length: {seq_len}")
|
| 81 |
-
print(f" - Input shape: {input_ids.shape}")
|
| 82 |
-
|
| 83 |
-
# ============================================================
|
| 84 |
-
# Step 3: Inference - Extract embeddings
|
| 85 |
-
# ============================================================
|
| 86 |
-
print("\n[Step 3] Extracting cell embeddings...")
|
| 87 |
-
|
| 88 |
-
with torch.no_grad():
|
| 89 |
-
outputs = model(input_ids, output_hidden_states=False)
|
| 90 |
-
|
| 91 |
-
# Get the pooled embedding (cell representation)
|
| 92 |
-
cell_embeddings = outputs.pooled_embedding
|
| 93 |
-
|
| 94 |
-
print(f"✓ Extraction complete!")
|
| 95 |
-
print(f" - Cell embeddings shape: {cell_embeddings.shape}")
|
| 96 |
-
print(f" - Pooling method used: {outputs.embedding_pooling}")
|
| 97 |
-
print(f" - Embedding type: {cell_embeddings.dtype}")
|
| 98 |
-
|
| 99 |
-
# ============================================================
|
| 100 |
-
# Step 4: Example downstream analyses
|
| 101 |
-
# ============================================================
|
| 102 |
-
print("\n[Step 4] Example downstream uses...")
|
| 103 |
-
|
| 104 |
-
# Example 1: Clustering (KMeans)
|
| 105 |
-
from sklearn.cluster import KMeans
|
| 106 |
-
n_clusters = 3
|
| 107 |
-
kmeans = KMeans(n_clusters=n_clusters, n_init=10)
|
| 108 |
-
clusters = kmeans.fit_predict(cell_embeddings.cpu().numpy())
|
| 109 |
-
print(f"✓ Clustering: Assigned {len(np.unique(clusters))} clusters")
|
| 110 |
-
|
| 111 |
-
# Example 2: Dimensionality reduction (PCA)
|
| 112 |
-
from sklearn.decomposition import PCA
|
| 113 |
-
pca = PCA(n_components=2)
|
| 114 |
-
embedding_2d = pca.fit_transform(cell_embeddings.cpu().numpy())
|
| 115 |
-
print(f"✓ PCA reduction: {cell_embeddings.shape} → {embedding_2d.shape}")
|
| 116 |
-
|
| 117 |
-
# Example 3: Similarity search
|
| 118 |
-
# Find the most similar cell to the first cell
|
| 119 |
-
similarities = torch.nn.functional.cosine_similarity(
|
| 120 |
-
cell_embeddings[0:1],
|
| 121 |
-
cell_embeddings
|
| 122 |
-
)
|
| 123 |
-
most_similar_idx = torch.argmax(similarities).item()
|
| 124 |
-
print(f"✓ Similarity search: Most similar cell to cell 0 is cell {most_similar_idx} "
|
| 125 |
-
f"(similarity: {similarities[most_similar_idx]:.4f})")
|
| 126 |
-
|
| 127 |
-
# Example 4: Statistics
|
| 128 |
-
print("\n[Step 5] Embedding statistics:")
|
| 129 |
-
print(f" - Mean: {cell_embeddings.mean(dim=0).norm():.4f}")
|
| 130 |
-
print(f" - Std: {cell_embeddings.std(dim=0).mean():.4f}")
|
| 131 |
-
print(f" - Min: {cell_embeddings.min():.4f}")
|
| 132 |
-
print(f" - Max: {cell_embeddings.max():.4f}")
|
| 133 |
-
|
| 134 |
-
# ============================================================
|
| 135 |
-
# Step 6: Save embeddings (optional)
|
| 136 |
-
# ============================================================
|
| 137 |
-
print("\n[Step 6] Saving embeddings...")
|
| 138 |
-
|
| 139 |
-
np.save("cell_embeddings.npy", cell_embeddings.cpu().numpy())
|
| 140 |
-
print("✓ Embeddings saved to 'cell_embeddings.npy'")
|
| 141 |
-
|
| 142 |
-
print("\n" + "=" * 80)
|
| 143 |
-
print("Phase 1 Complete!")
|
| 144 |
-
print("=" * 80)
|
| 145 |
-
|
| 146 |
-
return model, cell_embeddings
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
if __name__ == "__main__":
|
| 150 |
-
model, embeddings = main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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