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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
GeneSetCLIP Training Job — Self-contained script for HF Jobs.
|
| 4 |
+
|
| 5 |
+
Downloads MSigDB data from Hub, then trains the contrastive model.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 12 |
+
|
| 13 |
+
# Step 1: Download data from Hub
|
| 14 |
+
print("=" * 70)
|
| 15 |
+
print("Step 1: Downloading MSigDB data from Hub...")
|
| 16 |
+
print("=" * 70)
|
| 17 |
+
|
| 18 |
+
from huggingface_hub import hf_hub_download
|
| 19 |
+
|
| 20 |
+
DATA_DIR = "/tmp/data"
|
| 21 |
+
os.makedirs(DATA_DIR, exist_ok=True)
|
| 22 |
+
|
| 23 |
+
for split in ["train", "val", "test"]:
|
| 24 |
+
path = hf_hub_download(
|
| 25 |
+
repo_id="AliSaadatV/msigdb-contrastive-data",
|
| 26 |
+
filename=f"{split}.jsonl",
|
| 27 |
+
repo_type="dataset",
|
| 28 |
+
local_dir=DATA_DIR,
|
| 29 |
+
)
|
| 30 |
+
size_mb = os.path.getsize(path) / 1024 / 1024
|
| 31 |
+
print(f" {split}.jsonl: {size_mb:.1f} MB")
|
| 32 |
+
|
| 33 |
+
print("Data downloaded!\n")
|
| 34 |
+
|
| 35 |
+
# Step 2: Import and configure training
|
| 36 |
+
import json
|
| 37 |
+
import math
|
| 38 |
+
import random
|
| 39 |
+
import time
|
| 40 |
+
from collections import defaultdict
|
| 41 |
+
from dataclasses import dataclass
|
| 42 |
+
|
| 43 |
+
import torch
|
| 44 |
+
import torch.nn as nn
|
| 45 |
+
import torch.nn.functional as F
|
| 46 |
+
from torch.utils.data import Dataset, DataLoader
|
| 47 |
+
import numpy as np
|
| 48 |
+
from huggingface_hub import HfApi
|
| 49 |
+
import trackio
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ============================================================
|
| 53 |
+
# Configuration
|
| 54 |
+
# ============================================================
|
| 55 |
+
|
| 56 |
+
@dataclass
|
| 57 |
+
class Config:
|
| 58 |
+
gene_model_id: str = "maayanlab/gsfm-rummagene"
|
| 59 |
+
text_model_id: str = "FremyCompany/BioLORD-2023"
|
| 60 |
+
shared_dim: int = 256
|
| 61 |
+
gene_dim: int = 256
|
| 62 |
+
text_dim: int = 768
|
| 63 |
+
proj_hidden_dim: int = 512
|
| 64 |
+
proj_dropout: float = 0.1
|
| 65 |
+
batch_size: int = 256
|
| 66 |
+
lr: float = 1e-4
|
| 67 |
+
gene_encoder_lr: float = 1e-5
|
| 68 |
+
weight_decay: float = 0.01
|
| 69 |
+
warmup_steps: int = 500
|
| 70 |
+
max_epochs: int = 50
|
| 71 |
+
patience: int = 10
|
| 72 |
+
temperature_init: float = 0.07
|
| 73 |
+
learnable_temperature: bool = True
|
| 74 |
+
gene_dropout_rate: float = 0.2
|
| 75 |
+
max_gene_set_size: int = 512
|
| 76 |
+
data_dir: str = DATA_DIR
|
| 77 |
+
output_dir: str = "/tmp/output"
|
| 78 |
+
hub_model_id: str = "AliSaadatV/GeneSetCLIP"
|
| 79 |
+
device: str = "cuda" if torch.cuda.is_available() else "cpu"
|
| 80 |
+
num_workers: int = 4
|
| 81 |
+
mixed_precision: bool = True
|
| 82 |
+
log_every: int = 10
|
| 83 |
+
eval_every: int = 1
|
| 84 |
+
save_every: int = 5
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# ============================================================
|
| 88 |
+
# Dataset
|
| 89 |
+
# ============================================================
|
| 90 |
+
|
| 91 |
+
class GeneSetTextDataset(Dataset):
|
| 92 |
+
def __init__(self, jsonl_path, vocab, max_genes=512, gene_dropout=0.0, pad_idx=1):
|
| 93 |
+
self.records = []
|
| 94 |
+
with open(jsonl_path) as f:
|
| 95 |
+
for line in f:
|
| 96 |
+
self.records.append(json.loads(line))
|
| 97 |
+
self.vocab = vocab
|
| 98 |
+
self.max_genes = max_genes
|
| 99 |
+
self.gene_dropout = gene_dropout
|
| 100 |
+
self.pad_idx = pad_idx
|
| 101 |
+
|
| 102 |
+
def __len__(self):
|
| 103 |
+
return len(self.records)
|
| 104 |
+
|
| 105 |
+
def __getitem__(self, idx):
|
| 106 |
+
record = self.records[idx]
|
| 107 |
+
text = record["text"]
|
| 108 |
+
genes = record["genes"]
|
| 109 |
+
token_ids = [self.vocab.get(g, 0) for g in genes]
|
| 110 |
+
|
| 111 |
+
if self.gene_dropout > 0:
|
| 112 |
+
n_keep = max(3, int(len(token_ids) * (1 - self.gene_dropout)))
|
| 113 |
+
if n_keep < len(token_ids):
|
| 114 |
+
token_ids = random.sample(token_ids, n_keep)
|
| 115 |
+
|
| 116 |
+
if len(token_ids) > self.max_genes:
|
| 117 |
+
token_ids = random.sample(token_ids, self.max_genes)
|
| 118 |
+
|
| 119 |
+
n_genes = len(token_ids)
|
| 120 |
+
if n_genes < self.max_genes:
|
| 121 |
+
token_ids = token_ids + [self.pad_idx] * (self.max_genes - n_genes)
|
| 122 |
+
|
| 123 |
+
return {
|
| 124 |
+
"text": text,
|
| 125 |
+
"gene_ids": torch.tensor(token_ids, dtype=torch.long),
|
| 126 |
+
"n_genes": n_genes,
|
| 127 |
+
"id": record["id"],
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def collate_fn(batch):
|
| 132 |
+
return {
|
| 133 |
+
"text": [item["text"] for item in batch],
|
| 134 |
+
"gene_ids": torch.stack([item["gene_ids"] for item in batch]),
|
| 135 |
+
"n_genes": torch.tensor([item["n_genes"] for item in batch]),
|
| 136 |
+
"ids": [item["id"] for item in batch],
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# ============================================================
|
| 141 |
+
# Model
|
| 142 |
+
# ============================================================
|
| 143 |
+
|
| 144 |
+
class ProjectionHead(nn.Module):
|
| 145 |
+
def __init__(self, input_dim, hidden_dim, output_dim, dropout=0.1):
|
| 146 |
+
super().__init__()
|
| 147 |
+
self.net = nn.Sequential(
|
| 148 |
+
nn.Linear(input_dim, hidden_dim),
|
| 149 |
+
nn.GELU(),
|
| 150 |
+
nn.Dropout(dropout),
|
| 151 |
+
nn.Linear(hidden_dim, output_dim),
|
| 152 |
+
nn.LayerNorm(output_dim),
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
def forward(self, x):
|
| 156 |
+
return self.net(x)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class GeneSetCLIP(nn.Module):
|
| 160 |
+
def __init__(self, config):
|
| 161 |
+
super().__init__()
|
| 162 |
+
self.config = config
|
| 163 |
+
self.log_temperature = nn.Parameter(
|
| 164 |
+
torch.log(torch.tensor(config.temperature_init)),
|
| 165 |
+
requires_grad=config.learnable_temperature,
|
| 166 |
+
)
|
| 167 |
+
self.text_proj = ProjectionHead(config.text_dim, config.proj_hidden_dim,
|
| 168 |
+
config.shared_dim, config.proj_dropout)
|
| 169 |
+
self.gene_proj = ProjectionHead(config.gene_dim, config.shared_dim,
|
| 170 |
+
config.shared_dim, config.proj_dropout)
|
| 171 |
+
|
| 172 |
+
@property
|
| 173 |
+
def temperature(self):
|
| 174 |
+
return torch.clamp(self.log_temperature.exp(), min=0.01, max=1.0)
|
| 175 |
+
|
| 176 |
+
def forward(self, gene_emb, text_emb):
|
| 177 |
+
z_gene = F.normalize(self.gene_proj(gene_emb), dim=-1)
|
| 178 |
+
z_text = F.normalize(self.text_proj(text_emb), dim=-1)
|
| 179 |
+
tau = self.temperature
|
| 180 |
+
logits = z_gene @ z_text.T / tau
|
| 181 |
+
B = logits.size(0)
|
| 182 |
+
labels = torch.arange(B, device=logits.device)
|
| 183 |
+
loss_g2t = F.cross_entropy(logits, labels)
|
| 184 |
+
loss_t2g = F.cross_entropy(logits.T, labels)
|
| 185 |
+
loss = (loss_g2t + loss_t2g) / 2
|
| 186 |
+
with torch.no_grad():
|
| 187 |
+
g2t_acc = (logits.argmax(dim=1) == labels).float().mean()
|
| 188 |
+
t2g_acc = (logits.T.argmax(dim=1) == labels).float().mean()
|
| 189 |
+
avg_acc = (g2t_acc + t2g_acc) / 2
|
| 190 |
+
metrics = {
|
| 191 |
+
"loss": loss.item(), "g2t_acc": g2t_acc.item(),
|
| 192 |
+
"t2g_acc": t2g_acc.item(), "avg_acc": avg_acc.item(),
|
| 193 |
+
"temperature": tau.item(),
|
| 194 |
+
}
|
| 195 |
+
return loss, z_gene, z_text, metrics
|
| 196 |
+
|
| 197 |
+
def get_embeddings(self, gene_emb=None, text_emb=None):
|
| 198 |
+
z_gene = z_text = None
|
| 199 |
+
if gene_emb is not None:
|
| 200 |
+
z_gene = F.normalize(self.gene_proj(gene_emb), dim=-1)
|
| 201 |
+
if text_emb is not None:
|
| 202 |
+
z_text = F.normalize(self.text_proj(text_emb), dim=-1)
|
| 203 |
+
return z_gene, z_text
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# ============================================================
|
| 207 |
+
# Evaluation
|
| 208 |
+
# ============================================================
|
| 209 |
+
|
| 210 |
+
@torch.no_grad()
|
| 211 |
+
def evaluate_retrieval(model, gene_encoder, text_encoder, dataloader, device):
|
| 212 |
+
model.eval()
|
| 213 |
+
gene_encoder.eval()
|
| 214 |
+
all_z_gene, all_z_text, all_ids = [], [], []
|
| 215 |
+
total_loss, n_batches = 0, 0
|
| 216 |
+
|
| 217 |
+
for batch in dataloader:
|
| 218 |
+
gene_ids = batch["gene_ids"].to(device)
|
| 219 |
+
texts = batch["text"]
|
| 220 |
+
gene_emb = gene_encoder.encode(gene_ids)
|
| 221 |
+
text_emb = text_encoder.encode(texts, convert_to_tensor=True, show_progress_bar=False)
|
| 222 |
+
if text_emb.device != device:
|
| 223 |
+
text_emb = text_emb.to(device)
|
| 224 |
+
text_emb = text_emb.clone()
|
| 225 |
+
loss, z_gene, z_text, _ = model(gene_emb, text_emb)
|
| 226 |
+
total_loss += loss.item()
|
| 227 |
+
n_batches += 1
|
| 228 |
+
all_z_gene.append(z_gene.cpu())
|
| 229 |
+
all_z_text.append(z_text.cpu())
|
| 230 |
+
all_ids.extend(batch["ids"])
|
| 231 |
+
|
| 232 |
+
all_z_gene = torch.cat(all_z_gene, dim=0)
|
| 233 |
+
all_z_text = torch.cat(all_z_text, dim=0)
|
| 234 |
+
N = len(all_z_gene)
|
| 235 |
+
sim = all_z_gene @ all_z_text.T
|
| 236 |
+
labels = torch.arange(N)
|
| 237 |
+
|
| 238 |
+
def recall_at_k(sim_matrix, labels, k):
|
| 239 |
+
topk = sim_matrix.topk(min(k, sim_matrix.size(1)), dim=1).indices
|
| 240 |
+
return (topk == labels.unsqueeze(1)).any(dim=1).float().mean().item()
|
| 241 |
+
|
| 242 |
+
def mrr(sim_matrix, labels):
|
| 243 |
+
ranks = (sim_matrix.argsort(dim=1, descending=True) == labels.unsqueeze(1)).nonzero()[:, 1] + 1
|
| 244 |
+
return (1.0 / ranks.float()).mean().item()
|
| 245 |
+
|
| 246 |
+
results = {
|
| 247 |
+
"loss": total_loss / max(n_batches, 1), "n_samples": N,
|
| 248 |
+
"g2t_R@1": recall_at_k(sim, labels, 1),
|
| 249 |
+
"g2t_R@5": recall_at_k(sim, labels, 5),
|
| 250 |
+
"g2t_R@10": recall_at_k(sim, labels, 10),
|
| 251 |
+
"g2t_MRR": mrr(sim, labels),
|
| 252 |
+
"t2g_R@1": recall_at_k(sim.T, labels, 1),
|
| 253 |
+
"t2g_R@5": recall_at_k(sim.T, labels, 5),
|
| 254 |
+
"t2g_R@10": recall_at_k(sim.T, labels, 10),
|
| 255 |
+
"t2g_MRR": mrr(sim.T, labels),
|
| 256 |
+
}
|
| 257 |
+
results["avg_R@1"] = (results["g2t_R@1"] + results["t2g_R@1"]) / 2
|
| 258 |
+
results["avg_R@5"] = (results["g2t_R@5"] + results["t2g_R@5"]) / 2
|
| 259 |
+
results["avg_R@10"] = (results["g2t_R@10"] + results["t2g_R@10"]) / 2
|
| 260 |
+
results["avg_MRR"] = (results["g2t_MRR"] + results["t2g_MRR"]) / 2
|
| 261 |
+
|
| 262 |
+
model.train()
|
| 263 |
+
return results
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
# ============================================================
|
| 267 |
+
# Training
|
| 268 |
+
# ============================================================
|
| 269 |
+
|
| 270 |
+
def train(config):
|
| 271 |
+
print("=" * 70)
|
| 272 |
+
print("GeneSetCLIP Training")
|
| 273 |
+
print("=" * 70)
|
| 274 |
+
print(f"Device: {config.device}")
|
| 275 |
+
print(f"Batch size: {config.batch_size}")
|
| 276 |
+
print(f"Max epochs: {config.max_epochs}")
|
| 277 |
+
|
| 278 |
+
os.makedirs(config.output_dir, exist_ok=True)
|
| 279 |
+
|
| 280 |
+
# Load GSFM
|
| 281 |
+
print("\nLoading GSFM gene encoder...")
|
| 282 |
+
from gsfm import GSFM, Vocab
|
| 283 |
+
vocab_obj = Vocab.from_pretrained(config.gene_model_id)
|
| 284 |
+
gene_encoder = GSFM.from_pretrained(config.gene_model_id)
|
| 285 |
+
gene_encoder.to(config.device)
|
| 286 |
+
gene_encoder.train()
|
| 287 |
+
vocab_dict = {token: i for i, token in enumerate(vocab_obj.vocab)}
|
| 288 |
+
print(f" GSFM vocab: {len(vocab_dict)} genes")
|
| 289 |
+
|
| 290 |
+
# Load BioLORD (frozen)
|
| 291 |
+
print("Loading BioLORD text encoder (frozen)...")
|
| 292 |
+
from sentence_transformers import SentenceTransformer
|
| 293 |
+
text_encoder = SentenceTransformer(config.text_model_id, device=config.device)
|
| 294 |
+
for param in text_encoder.parameters():
|
| 295 |
+
param.requires_grad = False
|
| 296 |
+
text_encoder.eval()
|
| 297 |
+
|
| 298 |
+
# Model
|
| 299 |
+
print("Building GeneSetCLIP model...")
|
| 300 |
+
model = GeneSetCLIP(config).to(config.device)
|
| 301 |
+
print(f" Projection params: {sum(p.numel() for p in model.parameters() if p.requires_grad):,}")
|
| 302 |
+
print(f" Gene encoder params: {sum(p.numel() for p in gene_encoder.parameters()):,}")
|
| 303 |
+
|
| 304 |
+
# Data
|
| 305 |
+
print("\nLoading datasets...")
|
| 306 |
+
train_ds = GeneSetTextDataset(os.path.join(config.data_dir, "train.jsonl"),
|
| 307 |
+
vocab_dict, config.max_gene_set_size, config.gene_dropout_rate)
|
| 308 |
+
val_ds = GeneSetTextDataset(os.path.join(config.data_dir, "val.jsonl"),
|
| 309 |
+
vocab_dict, config.max_gene_set_size, 0.0)
|
| 310 |
+
test_ds = GeneSetTextDataset(os.path.join(config.data_dir, "test.jsonl"),
|
| 311 |
+
vocab_dict, config.max_gene_set_size, 0.0)
|
| 312 |
+
print(f" Train: {len(train_ds)}, Val: {len(val_ds)}, Test: {len(test_ds)}")
|
| 313 |
+
|
| 314 |
+
train_loader = DataLoader(train_ds, batch_size=config.batch_size, shuffle=True,
|
| 315 |
+
collate_fn=collate_fn, num_workers=config.num_workers,
|
| 316 |
+
pin_memory=True, drop_last=True)
|
| 317 |
+
val_loader = DataLoader(val_ds, batch_size=config.batch_size, shuffle=False,
|
| 318 |
+
collate_fn=collate_fn, num_workers=config.num_workers)
|
| 319 |
+
test_loader = DataLoader(test_ds, batch_size=config.batch_size, shuffle=False,
|
| 320 |
+
collate_fn=collate_fn, num_workers=config.num_workers)
|
| 321 |
+
|
| 322 |
+
steps_per_epoch = len(train_loader)
|
| 323 |
+
total_steps = steps_per_epoch * config.max_epochs
|
| 324 |
+
print(f" Steps/epoch: {steps_per_epoch}, Total: {total_steps}")
|
| 325 |
+
|
| 326 |
+
# Optimizer
|
| 327 |
+
optimizer = torch.optim.AdamW([
|
| 328 |
+
{"params": list(model.text_proj.parameters()) + list(model.gene_proj.parameters()) +
|
| 329 |
+
[model.log_temperature], "lr": config.lr, "weight_decay": config.weight_decay},
|
| 330 |
+
{"params": gene_encoder.parameters(), "lr": config.gene_encoder_lr,
|
| 331 |
+
"weight_decay": config.weight_decay},
|
| 332 |
+
])
|
| 333 |
+
|
| 334 |
+
def lr_lambda(step):
|
| 335 |
+
if step < config.warmup_steps:
|
| 336 |
+
return step / max(config.warmup_steps, 1)
|
| 337 |
+
progress = (step - config.warmup_steps) / max(total_steps - config.warmup_steps, 1)
|
| 338 |
+
return 0.5 * (1 + math.cos(math.pi * progress))
|
| 339 |
+
|
| 340 |
+
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
|
| 341 |
+
scaler = torch.amp.GradScaler('cuda') if config.mixed_precision and config.device == "cuda" else None
|
| 342 |
+
|
| 343 |
+
# Tracking
|
| 344 |
+
trackio.init(project="GeneSetCLIP",
|
| 345 |
+
name=f"bs{config.batch_size}_lr{config.lr}_temp{config.temperature_init}")
|
| 346 |
+
|
| 347 |
+
# Training loop
|
| 348 |
+
best_val_mrr = 0
|
| 349 |
+
patience_counter = 0
|
| 350 |
+
global_step = 0
|
| 351 |
+
|
| 352 |
+
for epoch in range(1, config.max_epochs + 1):
|
| 353 |
+
model.train()
|
| 354 |
+
gene_encoder.train()
|
| 355 |
+
epoch_loss, epoch_acc, n_batches = 0, 0, 0
|
| 356 |
+
|
| 357 |
+
for batch in train_loader:
|
| 358 |
+
gene_ids = batch["gene_ids"].to(config.device)
|
| 359 |
+
texts = batch["text"]
|
| 360 |
+
|
| 361 |
+
gene_emb = gene_encoder.encode(gene_ids)
|
| 362 |
+
with torch.no_grad():
|
| 363 |
+
text_emb = text_encoder.encode(texts, convert_to_tensor=True, show_progress_bar=False)
|
| 364 |
+
if text_emb.device != torch.device(config.device):
|
| 365 |
+
text_emb = text_emb.to(config.device)
|
| 366 |
+
text_emb = text_emb.clone()
|
| 367 |
+
|
| 368 |
+
if scaler is not None:
|
| 369 |
+
with torch.amp.autocast('cuda'):
|
| 370 |
+
loss, _, _, metrics = model(gene_emb, text_emb)
|
| 371 |
+
optimizer.zero_grad()
|
| 372 |
+
scaler.scale(loss).backward()
|
| 373 |
+
scaler.unscale_(optimizer)
|
| 374 |
+
torch.nn.utils.clip_grad_norm_(
|
| 375 |
+
list(model.parameters()) + list(gene_encoder.parameters()), 1.0)
|
| 376 |
+
scaler.step(optimizer)
|
| 377 |
+
scaler.update()
|
| 378 |
+
else:
|
| 379 |
+
loss, _, _, metrics = model(gene_emb, text_emb)
|
| 380 |
+
optimizer.zero_grad()
|
| 381 |
+
loss.backward()
|
| 382 |
+
torch.nn.utils.clip_grad_norm_(
|
| 383 |
+
list(model.parameters()) + list(gene_encoder.parameters()), 1.0)
|
| 384 |
+
optimizer.step()
|
| 385 |
+
|
| 386 |
+
scheduler.step()
|
| 387 |
+
global_step += 1
|
| 388 |
+
epoch_loss += metrics["loss"]
|
| 389 |
+
epoch_acc += metrics["avg_acc"]
|
| 390 |
+
n_batches += 1
|
| 391 |
+
|
| 392 |
+
if global_step % config.log_every == 0:
|
| 393 |
+
lr_p = optimizer.param_groups[0]["lr"]
|
| 394 |
+
lr_g = optimizer.param_groups[1]["lr"]
|
| 395 |
+
print(f" Step {global_step:5d} | Loss: {metrics['loss']:.4f} | "
|
| 396 |
+
f"Acc: {metrics['avg_acc']:.3f} | τ: {metrics['temperature']:.4f} | "
|
| 397 |
+
f"LR: {lr_p:.2e}/{lr_g:.2e}")
|
| 398 |
+
trackio.log({
|
| 399 |
+
"train/loss": metrics["loss"], "train/avg_acc": metrics["avg_acc"],
|
| 400 |
+
"train/g2t_acc": metrics["g2t_acc"], "train/t2g_acc": metrics["t2g_acc"],
|
| 401 |
+
"train/temperature": metrics["temperature"],
|
| 402 |
+
"train/lr_proj": lr_p, "train/lr_gene": lr_g, "step": global_step,
|
| 403 |
+
})
|
| 404 |
+
|
| 405 |
+
avg_loss = epoch_loss / max(n_batches, 1)
|
| 406 |
+
avg_acc = epoch_acc / max(n_batches, 1)
|
| 407 |
+
print(f"\nEpoch {epoch}/{config.max_epochs} | Loss: {avg_loss:.4f} | Acc: {avg_acc:.3f}")
|
| 408 |
+
|
| 409 |
+
# Validation
|
| 410 |
+
if epoch % config.eval_every == 0:
|
| 411 |
+
print(" Evaluating...")
|
| 412 |
+
val_results = evaluate_retrieval(model, gene_encoder, text_encoder,
|
| 413 |
+
val_loader, config.device)
|
| 414 |
+
print(f" Val R@1: {val_results['avg_R@1']:.3f} | R@5: {val_results['avg_R@5']:.3f} | "
|
| 415 |
+
f"MRR: {val_results['avg_MRR']:.3f}")
|
| 416 |
+
trackio.log({
|
| 417 |
+
"val/loss": val_results["loss"],
|
| 418 |
+
"val/avg_R@1": val_results["avg_R@1"],
|
| 419 |
+
"val/avg_R@5": val_results["avg_R@5"],
|
| 420 |
+
"val/avg_R@10": val_results["avg_R@10"],
|
| 421 |
+
"val/avg_MRR": val_results["avg_MRR"],
|
| 422 |
+
"epoch": epoch,
|
| 423 |
+
})
|
| 424 |
+
|
| 425 |
+
if val_results["avg_MRR"] > best_val_mrr:
|
| 426 |
+
best_val_mrr = val_results["avg_MRR"]
|
| 427 |
+
patience_counter = 0
|
| 428 |
+
save_dir = os.path.join(config.output_dir, "best_model")
|
| 429 |
+
os.makedirs(save_dir, exist_ok=True)
|
| 430 |
+
torch.save(model.state_dict(), os.path.join(save_dir, "clip_model.pt"))
|
| 431 |
+
torch.save(gene_encoder.state_dict(), os.path.join(save_dir, "gene_encoder.pt"))
|
| 432 |
+
with open(os.path.join(save_dir, "config.json"), "w") as f:
|
| 433 |
+
json.dump(vars(config), f, indent=2)
|
| 434 |
+
print(f" ✓ New best! MRR: {best_val_mrr:.4f}")
|
| 435 |
+
else:
|
| 436 |
+
patience_counter += 1
|
| 437 |
+
print(f" No improvement ({patience_counter}/{config.patience})")
|
| 438 |
+
if patience_counter >= config.patience:
|
| 439 |
+
print(f" Early stopping at epoch {epoch}")
|
| 440 |
+
break
|
| 441 |
+
|
| 442 |
+
# Load best model
|
| 443 |
+
print("\n" + "=" * 70)
|
| 444 |
+
print("Final test evaluation...")
|
| 445 |
+
best_path = os.path.join(config.output_dir, "best_model")
|
| 446 |
+
if os.path.exists(best_path):
|
| 447 |
+
model.load_state_dict(torch.load(os.path.join(best_path, "clip_model.pt"),
|
| 448 |
+
map_location=config.device, weights_only=True))
|
| 449 |
+
gene_encoder.load_state_dict(torch.load(os.path.join(best_path, "gene_encoder.pt"),
|
| 450 |
+
map_location=config.device, weights_only=True))
|
| 451 |
+
|
| 452 |
+
test_results = evaluate_retrieval(model, gene_encoder, text_encoder,
|
| 453 |
+
test_loader, config.device)
|
| 454 |
+
print(f"Test Results:")
|
| 455 |
+
print(f" G→T R@1: {test_results['g2t_R@1']:.3f} R@5: {test_results['g2t_R@5']:.3f} R@10: {test_results['g2t_R@10']:.3f} MRR: {test_results['g2t_MRR']:.3f}")
|
| 456 |
+
print(f" T→G R@1: {test_results['t2g_R@1']:.3f} R@5: {test_results['t2g_R@5']:.3f} R@10: {test_results['t2g_R@10']:.3f} MRR: {test_results['t2g_MRR']:.3f}")
|
| 457 |
+
print(f" Avg R@1: {test_results['avg_R@1']:.3f} R@5: {test_results['avg_R@5']:.3f} MRR: {test_results['avg_MRR']:.3f}")
|
| 458 |
+
trackio.log({"test/" + k: v for k, v in test_results.items()})
|
| 459 |
+
|
| 460 |
+
# Push to Hub
|
| 461 |
+
print("\nPushing to Hub...")
|
| 462 |
+
api = HfApi()
|
| 463 |
+
try:
|
| 464 |
+
api.create_repo(config.hub_model_id, exist_ok=True)
|
| 465 |
+
except Exception as e:
|
| 466 |
+
print(f" Warning: {e}")
|
| 467 |
+
|
| 468 |
+
upload_dir = os.path.join(config.output_dir, "hub_upload")
|
| 469 |
+
os.makedirs(upload_dir, exist_ok=True)
|
| 470 |
+
torch.save(model.state_dict(), os.path.join(upload_dir, "clip_model.pt"))
|
| 471 |
+
torch.save(gene_encoder.state_dict(), os.path.join(upload_dir, "gene_encoder.pt"))
|
| 472 |
+
with open(os.path.join(upload_dir, "config.json"), "w") as f:
|
| 473 |
+
json.dump(vars(config), f, indent=2)
|
| 474 |
+
with open(os.path.join(upload_dir, "vocab.json"), "w") as f:
|
| 475 |
+
json.dump(vocab_dict, f)
|
| 476 |
+
with open(os.path.join(upload_dir, "test_results.json"), "w") as f:
|
| 477 |
+
json.dump(test_results, f, indent=2)
|
| 478 |
+
|
| 479 |
+
readme = f"""# GeneSetCLIP
|
| 480 |
+
|
| 481 |
+
Contrastive model aligning gene-set embeddings (GSFM) with biomedical text descriptions (BioLORD-2023).
|
| 482 |
+
|
| 483 |
+
## Architecture
|
| 484 |
+
- **Gene encoder**: [GSFM](https://huggingface.co/maayanlab/gsfm-rummagene) (MLP autoencoder, 256-dim)
|
| 485 |
+
- **Text encoder**: [BioLORD-2023](https://huggingface.co/FremyCompany/BioLORD-2023) (768-dim, frozen)
|
| 486 |
+
- **Projection heads**: Maps both modalities to shared 256-dim space
|
| 487 |
+
- **Loss**: Symmetric InfoNCE with learnable temperature
|
| 488 |
+
|
| 489 |
+
## Training Data
|
| 490 |
+
- **MSigDB v2024.1** (Human + Mouse): ~50,000 gene set-text pairs
|
| 491 |
+
- Collections: H, C1-C8 (Human), MH, M1-M8 (Mouse)
|
| 492 |
+
- Train: C2/C5/C8/C1 | Val: C3/C4 | Test: H/C6/C7
|
| 493 |
+
|
| 494 |
+
## Test Results (H, C6, C7 — {test_results['n_samples']} gene sets)
|
| 495 |
+
| Metric | Gene→Text | Text→Gene | Average |
|
| 496 |
+
|--------|-----------|-----------|---------|
|
| 497 |
+
| R@1 | {test_results['g2t_R@1']:.3f} | {test_results['t2g_R@1']:.3f} | {test_results['avg_R@1']:.3f} |
|
| 498 |
+
| R@5 | {test_results['g2t_R@5']:.3f} | {test_results['t2g_R@5']:.3f} | {test_results['avg_R@5']:.3f} |
|
| 499 |
+
| R@10 | {test_results['g2t_R@10']:.3f} | {test_results['t2g_R@10']:.3f} | {test_results['avg_R@10']:.3f} |
|
| 500 |
+
| MRR | {test_results['g2t_MRR']:.3f} | {test_results['t2g_MRR']:.3f} | {test_results['avg_MRR']:.3f} |
|
| 501 |
+
|
| 502 |
+
## Usage
|
| 503 |
+
|
| 504 |
+
```python
|
| 505 |
+
import torch
|
| 506 |
+
from gsfm import GSFM, Vocab
|
| 507 |
+
from sentence_transformers import SentenceTransformer
|
| 508 |
+
from huggingface_hub import hf_hub_download
|
| 509 |
+
|
| 510 |
+
# Load gene encoder + vocab
|
| 511 |
+
gene_encoder = GSFM.from_pretrained("maayanlab/gsfm-rummagene")
|
| 512 |
+
vocab = Vocab.from_pretrained("maayanlab/gsfm-rummagene")
|
| 513 |
+
gene_encoder.eval()
|
| 514 |
+
|
| 515 |
+
# Load text encoder
|
| 516 |
+
text_encoder = SentenceTransformer("FremyCompany/BioLORD-2023")
|
| 517 |
+
|
| 518 |
+
# Load GeneSetCLIP projection heads
|
| 519 |
+
clip_path = hf_hub_download("AliSaadatV/GeneSetCLIP", "clip_model.pt")
|
| 520 |
+
config_path = hf_hub_download("AliSaadatV/GeneSetCLIP", "config.json")
|
| 521 |
+
|
| 522 |
+
import json
|
| 523 |
+
with open(config_path) as f:
|
| 524 |
+
cfg = json.load(f)
|
| 525 |
+
|
| 526 |
+
# Reconstruct model (small — just projection heads)
|
| 527 |
+
import torch.nn as nn, torch.nn.functional as F
|
| 528 |
+
|
| 529 |
+
class ProjectionHead(nn.Module):
|
| 530 |
+
def __init__(self, input_dim, hidden_dim, output_dim, dropout=0.1):
|
| 531 |
+
super().__init__()
|
| 532 |
+
self.net = nn.Sequential(nn.Linear(input_dim, hidden_dim), nn.GELU(),
|
| 533 |
+
nn.Dropout(dropout), nn.Linear(hidden_dim, output_dim),
|
| 534 |
+
nn.LayerNorm(output_dim))
|
| 535 |
+
def forward(self, x): return self.net(x)
|
| 536 |
+
|
| 537 |
+
class GeneSetCLIP(nn.Module):
|
| 538 |
+
def __init__(self):
|
| 539 |
+
super().__init__()
|
| 540 |
+
self.log_temperature = nn.Parameter(torch.zeros(1))
|
| 541 |
+
self.text_proj = ProjectionHead(768, 512, 256, 0.1)
|
| 542 |
+
self.gene_proj = ProjectionHead(256, 256, 256, 0.1)
|
| 543 |
+
|
| 544 |
+
clip_model = GeneSetCLIP()
|
| 545 |
+
clip_model.load_state_dict(torch.load(clip_path, map_location="cpu", weights_only=True))
|
| 546 |
+
clip_model.eval()
|
| 547 |
+
|
| 548 |
+
# Encode a gene set
|
| 549 |
+
genes = ["TP53", "BRCA1", "EGFR", "MYC", "KRAS"]
|
| 550 |
+
gene_ids = torch.tensor([vocab(genes)])
|
| 551 |
+
with torch.no_grad():
|
| 552 |
+
gene_emb = gene_encoder.encode(gene_ids)
|
| 553 |
+
z_gene = F.normalize(clip_model.gene_proj(gene_emb), dim=-1)
|
| 554 |
+
|
| 555 |
+
# Encode text
|
| 556 |
+
text_emb = text_encoder.encode(["Tumor suppressor genes involved in cancer"],
|
| 557 |
+
convert_to_tensor=True)
|
| 558 |
+
with torch.no_grad():
|
| 559 |
+
z_text = F.normalize(clip_model.text_proj(text_emb), dim=-1)
|
| 560 |
+
|
| 561 |
+
# Similarity
|
| 562 |
+
print(f"Similarity: {{(z_gene @ z_text.T).item():.3f}}")
|
| 563 |
+
```
|
| 564 |
+
"""
|
| 565 |
+
with open(os.path.join(upload_dir, "README.md"), "w") as f:
|
| 566 |
+
f.write(readme)
|
| 567 |
+
|
| 568 |
+
api.upload_folder(folder_path=upload_dir, repo_id=config.hub_model_id,
|
| 569 |
+
commit_message="Upload GeneSetCLIP trained model")
|
| 570 |
+
print(f" Pushed to https://huggingface.co/{config.hub_model_id}")
|
| 571 |
+
print("\nDone!")
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
if __name__ == "__main__":
|
| 575 |
+
config = Config()
|
| 576 |
+
train(config)
|