Spaces:
sebps
/
Sleeping

cellgemma / engine.py
sebps's picture
Update engine.py
8304333 verified
Raw History Blame Contribute Delete
45.2 kB
"""Core CellGemma Two-Stage Single-Cell Inference & 3D Molecular/Network Engine."""
from __future__ import annotations
import json
import math
import os
import queue
import re
import threading
import time
from pathlib import Path
from typing import Any, Iterator
import numpy as np
import safetensors.torch
import torch
from huggingface_hub import hf_hub_download
from rdkit import Chem
from rdkit.Chem import AllChem, Descriptors, rdDepictor, rdMolDescriptors
from torch import nn
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
DEFAULT_MODEL_ID = os.environ.get("CELLGEMMA_MODEL_ID", "google/cellgemma-e4b")
IS_ZEROGPU = os.environ.get("SPACES_ZERO_GPU") == "1"
PREAMBLE = (
"Examine how the single-cell sample, captured in 'Source:', responds "
"transcriptionally to the perturbation under the stated experimental "
"conditions. You are given the dataset-wide average prediction in 'Mean "
"Global prediction:' and you need to predict the residual from that mean "
"to the true final expression."
)
SMILES_ALLOW_RE = re.compile(r"^[A-Za-z0-9@+\-\[\]\(\)=#$%/\\.,]{1,200}$")
GENE_ALLOW_RE = re.compile(r"^[A-Z0-9\-]{1,20}$")
CURATED_PRESETS: list[dict[str, Any]] = [
{
"id": "panobinostat",
"dataset": "tahoe",
"kind": "drug",
"name": "Panobinostat",
"role": "HDAC Inhibitor · Unpacks DNA & Raises Surface Flags",
"smiles": "Cc1[nH]c2ccccc2c1CCNCc1ccc(/C=C/C(=O)NO)cc1",
"concentration_um": 0.5,
"cell_idx": 0,
"summary": "Relaxes tightly packed chromatin in A549 lung-cancer cells, turning up histones (+H1-0, +H3-3B) and 'eat-me' surface flag +CALR while turning down p53 brake -MDM2.",
},
{
"id": "dasatinib",
"dataset": "tahoe",
"kind": "drug",
"name": "Dasatinib",
"role": "Kinase Inhibitor · Blocks Invasion Receptors",
"smiles": "Cc1nc(Nc2ncc(C(=O)Nc3c(C)cccc3Cl)s2)cc(N2CCN(CCO)CC2)n1",
"concentration_um": 0.5,
"cell_idx": 0,
"summary": "Inhibits SRC/ABL/EPHA2 kinases in A549 lung-cancer cells, turning down invasion & growth receptors (-LRP1, -IGFBP3) while remodeling structural filaments (+VIM, +PLOD2).",
},
{
"id": "trametinib",
"dataset": "tahoe",
"kind": "drug",
"name": "Trametinib",
"role": "MEK1/2 Inhibitor · Cuts MAPK Growth Relay",
"smiles": "CC(=O)Nc1cccc(-n2c(=O)n(C3CC3)c(=O)c3c(Nc4ccc(I)cc4F)n(C)c(=O)c(C)c32)c1",
"concentration_um": 0.5,
"cell_idx": 0,
"summary": "Blocks MEK1/2 signaling downstream of KRAS in A549 cells, suppressing migration/MAPK feedback genes (-ARHGAP26, -LRP1, -DUSP5) and boosting redox defense (+TXNRD1).",
},
{
"id": "myc_kd",
"dataset": "k562",
"kind": "crispr",
"name": "Mute MYC",
"role": "Master Growth Oncogene · Collapses Ribosome Factories",
"gene": "MYC",
"concentration_um": 1.0,
"cell_idx": 0,
"summary": "CRISPRi knockdown of master growth switch MYC in K562 leukemia cells shuts down ribosome & polyamine factories (-C1QBP, -SRM, -WDR43, -RRP1B) and switches on red-blood-cell maturation (+GYPB, +HBZ, +ALAS2, +HBG2).",
},
{
"id": "dnmt1_kd",
"dataset": "k562",
"kind": "crispr",
"name": "Mute DNMT1",
"role": "DNA Methylation Lock · Lifts Epigenetic Silencing",
"gene": "DNMT1",
"concentration_um": 1.0,
"cell_idx": 0,
"summary": "CRISPRi knockdown of DNA methyltransferase DNMT1 lifts epigenetic silencing, exposing surface & secreted proteins (+SLC7A8, +LGALS1, +MDK) while suppressing nucleolar assembly (-NOLC1, -MRTO4).",
},
]
# Conservation intégrale des annotations de gènes originales
GENE_ANNOTATIONS: dict[str, tuple[str, str, str]] = {
"CALR": ("surface", "Calreticulin 'Eat-Me' Flag", "Surface chaperone that flags stressed tumor cells for immune engulfment."),
"B2M": ("surface", "MHC-I Antigen Presentation", "Essential MHC Class I subunit enabling T-cells to inspect tumor antigens."),
"GPNMB": ("surface", "CAR-T Surface Beacon", "Transmembrane glycoprotein targeted by solid-tumor CAR-T immunotherapies."),
"MAGEA10": ("surface", "Cancer-Testis Immune Antigen", "Normally silent germline antigen unmasked on demethylated tumor cells."),
"PAGE5": ("surface", "Unmasked Tumor Antigen", "Cancer-testis antigen awakened when DNA methylation locks are removed."),
"GYPB": ("surface", "Glycophorin B Red-Cell Coat", "Major red-blood-cell membrane coat protein induced as K562 matures."),
"GYPC": ("surface", "Glycophorin C Membrane Coat", "Erythroid plasma-membrane glycoprotein stabilizing mature red cells."),
"LGALS1": ("surface", "Galectin-1 Surface Lectin", "Cell-surface carbohydrate-binding protein remodeled during lineage shifts."),
"MDK": ("surface", "Midkine Secreted Signal", "Secreted growth/immune signaling factor induced upon epigenetic remodeling."),
"SLC7A8": ("surface", "LAT2 Surface Transporter", "Plasma-membrane neutral amino-acid channel awakened after demethylation."),
"AQP3": ("surface", "Aquaporin-3 Water Channel", "Cell-membrane water/glycerol pore upregulated during differentiation."),
"CAVIN1": ("surface", "Caveolae Membrane Sculptor", "Stabilizes plasma-membrane signaling pockets under MEK blockade."),
"AREG": ("surface", "Amphiregulin EGFR Ligand", "Secreted cell-surface growth-factor feedback signal."),
"LRP1": ("surface", "LRP1 Invasion Receptor", "Large cell-surface endocytic & migration receptor suppressed by kinase blockade."),
"PTPRJ": ("surface", "DEP-1 Surface Phosphatase", "Transmembrane receptor tyrosine phosphatase remodeled at cell junctions."),
"CA12": ("surface", "Hypoxia Acid-Shield (CA12)", "Cell-surface carbonic anhydrase helping tumor cells survive acidic niches."),
"SERPINE1": ("surface", "PAI-1 Matrix Invasion Shield", "Secreted adhesion & extracellular matrix regulator driving tumor migration."),
"IGFBP3": ("surface", "IGF Growth-Factor Carrier", "Extracellular growth-factor binding protein suppressed by kinase inhibition."),
"STC1": ("surface", "Stanniocalcin-1 Secreted Signal", "Secreted calcium/hypoxia survival hormone downregulated by MEK inhibition."),
"ADAM9": ("surface", "ADAM9 Surface Sheddase", "Membrane metalloprotease remodeling cell-surface receptors."),
"MYOF": ("surface", "Myoferlin Membrane Repair", "Plasma-membrane repair protein induced under signaling stress."),
"EPHA2": ("surface", "EPHA2 Surface Kinase", "Ephrin receptor tyrosine kinase regulating adhesion and surface antigen levels."),
"EGFR": ("surface", "EGFR Growth Receptor", "Transmembrane growth-factor antenna driving epithelial proliferation."),
"ITGA2": ("surface", "Integrin Alpha-2 Hook", "Surface collagen-adhesion receptor downregulated when MAPK signaling drops."),
"ICAM1": ("surface", "ICAM-1 Immune Docking Velcro", "Adhesion ligand stabilizing physical contact with immune T-cells."),
"ANXA1": ("surface", "Annexin A1 Membrane Signal", "Phospholipid-binding surface modulator induced during differentiation."),
"SEMA4B": ("surface", "Semaphorin-4B Surface Cue", "Transmembrane guidance receptor remodeled under Src/RTK kinase blockade."),
"H1-0": ("nucleus", "Linker Histone H1.0", "Terminal-differentiation histone induced when HDAC inhibitors unpack DNA."),
"H3-3B": ("nucleus", "Active Histone H3.3B", "Replacement histone loaded into newly opened, active DNA regions."),
"H1-2": ("nucleus", "Linker Histone H1.2", "Nuclear chromatin-compaction histone remodeled upon cell-cycle exit."),
"H1-4": ("nucleus", "Replication Histone H1.4", "S-phase chromatin linker downregulated as rapid division slows."),
"NAP1L1": ("nucleus", "Histone Chaperone NAP1L1", "Shuttles histones into the nucleus to assemble nucleosomes."),
"SMAD3": ("nucleus", "TGF-Beta Nuclear Regulator", "Transcription factor driving pro-tumor mesenchymal & survival programs."),
"MDM2": ("nucleus", "p53 Suppressor Brake (MDM2)", "Destroys tumor-suppressor p53; turning MDM2 down unleashes p53 checkpoints."),
"NRIP1": ("nucleus", "Nuclear Receptor Co-Repressor", "Transcriptional co-regulator modulating hormone and metabolic genes."),
"CDKN1A": ("nucleus", "p21 Cell-Division Brake", "Directly locks nuclear cyclin-CDK motors to halt tumor cell division."),
"GADD45A": ("nucleus", "DNA Stress Arrest Sensor", "Nuclear checkpoint protein induced when MYC proliferation stops."),
"CCND3": ("nucleus", "Cyclin D3 Lineage Switch", "Coordinates final erythroid maturation divisions before growth exit."),
"MYC": ("nucleus", "MYC Master Growth Switch", "Oncogenic transcription factor driving cell division and ribosome production."),
"DNMT1": ("nucleus", "DNA Methylation Lock (DNMT1)", "Copies repressive methyl marks onto DNA to keep genes silenced."),
"USP34": ("nucleus", "Wnt Signaling Stabilizer", "Deubiquitinase sustaining nuclear beta-catenin survival transcription."),
"DUSP5": ("nucleus", "Nuclear ERK Phosphatase", "Direct nuclear feedback readout of active MAPK/ERK growth signaling; drops under MEK blockade."),
"HSPA5": ("cytoplasm", "BiP ER Stress Chaperone", "Master endoplasmic-reticulum protein-folding sensor induced by HDAC inhibition."),
"HSP90B1": ("cytoplasm", "Grp94 Folding Chaperone", "ER chaperone folding secreted & immune-presentation proteins."),
"HSP90AA1": ("cytoplasm", "HSP90-Alpha Chaperone", "Stress-inducible cytosolic chaperone hyperacetylated by Panobinostat."),
"HBZ": ("cytoplasm", "Embryonic Zeta-Globin", "Oxygen-binding hemoglobin chain switched on as K562 matures into a red cell."),
"HBG2": ("cytoplasm", "Fetal Hemoglobin Gamma-2", "Hallmark oxygen-carrying hemoglobin induced during leukemia differentiation."),
"ALAS2": ("cytoplasm", "Heme Synthesis Enzyme ALAS2", "Rate-limiting enzyme building red-blood-cell heme groups."),
"C1QBP": ("cytoplasm", "Mitochondrial Protein Factory", "Direct MYC target powering oxidative metabolism; drops sharply when MYC is muted."),
"SRM": ("cytoplasm", "Spermidine Synthase (MYC Target)", "Canonical MYC-driven polyamine growth enzyme; collapses on MYC knockdown."),
"TXNRD1": ("cytoplasm", "Thioredoxin Reductase Antioxidant", "Protects cells against oxidative stress when MAPK signaling is blocked."),
"PLOD2": ("cytoplasm", "Collagen Cross-Linking Enzyme", "ER hydroxylase remodeled during tyrosine-kinase inhibition."),
"VIM": ("cytoplasm", "Vimentin Structural Filament", "Intermediate cytoskeleton filament reorganized as cell shape & motility shift."),
"ARHGAP26": ("cytoplasm", "FAK/Rho Migration Regulator", "Focal-adhesion GTPase regulator downregulated when MEK signaling stops."),
}
_LOC_CODE_MAP = {"n": "nucleus", "s": "surface", "c": "cytoplasm"}
def _load_gene_catalog() -> dict[str, list[str]]:
here = Path(__file__).resolve().parent
for candidate in (here / "gene_catalog.json", here.parent / "data" / "gene_catalog.json"):
if candidate.is_file():
try:
with open(candidate, encoding="utf-8") as f:
return json.load(f)
except Exception:
return {}
return {}
GENE_CATALOG: dict[str, list[str]] = _load_gene_catalog()
def _infer_fallback_annotation(gene: str, partners: list[str]) -> tuple[str, str, str]:
partner_str = f" Interacts with {', '.join(partners[:4])}." if partners else ""
cat = GENE_CATALOG.get(gene)
if cat and len(cat) >= 2:
loc = _LOC_CODE_MAP.get(cat[0], "cytoplasm")
short_name = cat[1]
return (loc, short_name, f"{short_name} ({gene}).{partner_str}")
if gene.startswith(("RPL", "RPS")):
return ("cytoplasm", f"Ribosomal Subunit ({gene})", f"Cytoplasmic protein-synthesis ribosome component.{partner_str}")
if gene.startswith("MRPL") or gene.startswith("MRPS") or gene.startswith("MT-"):
return ("cytoplasm", f"Mitochondrial Energy Subunit ({gene})", f"Mitochondrial respiratory or translation subunit.{partner_str}")
if gene.startswith(("H1-", "H2A", "H2B", "H3-", "H4", "HIST", "ZNF", "POLR", "SNRP", "SF3", "SRSF", "HNRNP")):
return ("nucleus", f"Nuclear Splicing / Chromatin ({gene})", f"Nuclear RNA processing or chromatin regulator.{partner_str}")
if gene.startswith(("SLC", "CD", "HLA-", "ITG", "EPH", "FZD", "GPR", "TMEM", "ATP1", "AQP")):
return ("surface", f"Membrane Channel / Receptor ({gene})", f"Cell-surface transmembrane transport or signaling protein.{partner_str}")
if gene.startswith(("HSP", "DNAJ", "BAG")):
return ("cytoplasm", f"Protein-Folding Chaperone ({gene})", f"Cellular stress-response folding chaperone.{partner_str}")
return ("cytoplasm", f"{gene} Cellular Factor", f"Differentially expressed protein-coding gene ({gene}).{partner_str}")
class ExpressionDecoder(nn.Module):
def __init__(self, input_dim: int, hidden_dims: list[int], max_exp_arg: float = 88.0):
super().__init__()
self.input_dim = input_dim
self.max_exp_arg = max_exp_arg
self.bn0 = nn.BatchNorm1d(input_dim + 1)
layers: list[nn.Module] = [self.bn0]
d = input_dim + 1
for h in hidden_dims:
layers += [nn.Linear(d, h), nn.ReLU()]
d = h
self.mlp = nn.Sequential(*layers, nn.Linear(d, 1))
def forward(self, features: torch.Tensor, control_expression: torch.Tensor) -> torch.Tensor:
eps = 1e-6
ctrl = control_expression.view(-1, 1)
x = self.mlp(torch.cat([features, ctrl], dim=1))
ctrl_safe = ctrl - torch.where(x >= 0, eps, -eps)
exp_term = (x / ctrl_safe).clamp(max=self.max_exp_arg)
neg_delta = ctrl_safe * (torch.exp(exp_term) - 1.0)
return torch.where(x > 0, x, neg_delta) + eps
def parse_smiles_2d(smiles: str, new_atom_start: int | None = None) -> dict[str, Any]:
cleaned = smiles.strip()
if not SMILES_ALLOW_RE.match(cleaned):
raise ValueError("Invalid characters or length in SMILES string.")
mol = Chem.MolFromSmiles(cleaned)
if mol is None or mol.GetNumAtoms() == 0 or mol.GetNumAtoms() > 120:
raise ValueError("Could not parse chemical SMILES into a valid molecule.")
canonical = Chem.MolToSmiles(mol, canonical=True)
mol_base = Chem.MolFromSmiles(canonical)
assert mol_base is not None
rdDepictor.Compute2DCoords(mol_base)
conf_2d = mol_base.GetConformer()
coords_3d: list[tuple[float, float, float]] = []
try:
mol_h = Chem.AddHs(Chem.MolFromSmiles(canonical))
params = AllChem.ETKDGv3()
params.randomSeed = 42
status = AllChem.EmbedMolecule(mol_h, params)
if status == 0:
AllChem.MMFFOptimizeMolecule(mol_h, maxIters=100)
mol_3d = Chem.RemoveHs(mol_h)
conf_3d = mol_3d.GetConformer()
for idx in range(mol_3d.GetNumAtoms()):
p = conf_3d.GetAtomPosition(idx)
coords_3d.append((float(p.x), float(p.y), float(p.z)))
except Exception:
coords_3d = []
if len(coords_3d) != mol_base.GetNumAtoms():
coords_3d = []
for idx in range(mol_base.GetNumAtoms()):
p = conf_2d.GetAtomPosition(idx)
coords_3d.append((float(p.x), float(-p.y), math.sin(idx * 0.9) * 0.25))
arr = np.array(coords_3d, dtype=np.float64)
arr -= arr.mean(axis=0, keepdims=True)
max_r = float(np.max(np.linalg.norm(arr, axis=1))) if len(arr) > 1 else 1.0
scale = 1.85 / max(1.0, max_r)
arr *= scale
nodes = []
for idx, atom in enumerate(mol_base.GetAtoms()):
p2 = conf_2d.GetAtomPosition(idx)
nodes.append({
"id": idx,
"elem": atom.GetSymbol(),
"x": round(float(arr[idx, 0]), 4),
"y": round(float(arr[idx, 1]), 4),
"z": round(float(arr[idx, 2]), 4),
"x2d": round(float(p2.x), 4),
"y2d": round(float(-p2.y), 4),
"aromatic": bool(atom.GetIsAromatic()),
"isNew": bool(new_atom_start is not None and idx >= new_atom_start),
})
edges = []
for bond in mol_base.GetBonds():
btype = bond.GetBondTypeAsDouble()
edges.append({
"a": bond.GetBeginAtomIdx(),
"b": bond.GetEndAtomIdx(),
"order": 2 if btype == 2.0 else (3 if btype == 3.0 else 1),
"aromatic": bool(bond.GetIsAromatic()),
})
return {
"mode": "drug",
"canonical_smiles": canonical,
"num_atoms": mol_base.GetNumHeavyAtoms(),
"mol_weight": round(float(Descriptors.MolWt(mol_base)), 1),
"num_rings": int(rdMolDescriptors.CalcNumRings(mol_base)),
"nodes": nodes,
"edges": edges,
}
class CellGemmaEngine:
def __init__(self, model_id: str = DEFAULT_MODEL_ID):
self.model_id = model_id
self.hf_token = os.environ.get("HF_TOKEN") or None
self.device, self.dtype = self._select_device()
self._model: AutoModelForCausalLM | None = None
self._tokenizer: AutoTokenizer | None = None
self._model_lock = threading.Lock()
self._load_lock = threading.Lock()
self.model_load_state: str = "not_loaded"
self.model_load_started_at: float = 0.0
self.model_load_error: str = ""
self.controls_all: dict[str, Any] = {}
self.kg: dict[str, str] = {}
self.decoders: dict[str, tuple[ExpressionDecoder, dict[str, float]]] = {}
self.genes_by_ds: dict[str, list[str]] = {}
self.gene_to_idx_by_ds: dict[str, dict[str, int]] = {}
# Cache pour les cellules téléchargées dynamiquement depuis les APIs (CELLxGENE / HPA)
self.custom_cell_profiles: dict[str, dict[str, Any]] = {}
self._load_lightweight_assets()
if IS_ZEROGPU:
self.ensure_model_loaded()
@staticmethod
def _select_device() -> tuple[str, torch.dtype]:
if IS_ZEROGPU or torch.cuda.is_available():
return "cuda", torch.bfloat16
if torch.backends.mps.is_available():
return "mps", torch.bfloat16
default_threads = min(32, max(4, (os.cpu_count() or 8) // 2))
cpu_threads = int(os.environ.get("CELLGEMMA_CPU_THREADS", str(default_threads)))
torch.set_num_threads(cpu_threads)
return "cpu", torch.float32
def _download_json(self, filename: str) -> Any:
path = hf_hub_download(self.model_id, filename, token=self.hf_token)
with open(path, encoding="utf-8") as f:
return json.load(f)
def _load_lightweight_assets(self) -> None:
self.controls_all = self._download_json("controls_sample.json")
self.kg = self._download_json("kg_sentences.json")
for ds in ("tahoe", "k562"):
cfg = self._download_json(f"decoders/{ds}/config.json")
dec = ExpressionDecoder(cfg["input_dim"], cfg["hidden_dims"])
weights_path = hf_hub_download(
self.model_id, f"decoders/{ds}/model.safetensors", token=self.hf_token
)
dec.load_state_dict(safetensors.torch.load_file(weights_path))
dec.eval()
raw_deltas = self._download_json(f"decoders/{ds}/mean_delta_global.json")
mean_deltas = {k.upper(): float(v) for k, v in raw_deltas.items()}
self.decoders[ds] = (dec, mean_deltas)
genes = [g.upper() for g in self.controls_all[ds]["genes"]]
self.genes_by_ds[ds] = genes
self.gene_to_idx_by_ds[ds] = {g: i for i, g in enumerate(genes)}
def register_custom_cell(self, cell_key: str, cell_name: str, expression_map: dict[str, float], base_dataset: str = "tahoe") -> dict[str, Any]:
"""Enregistre un profil cellulaire téléchargé depuis une API externe."""
genes = self.genes_by_ds.get(base_dataset, self.genes_by_ds["tahoe"])
vec = np.array([float(expression_map.get(g, 0.0)) for g in genes], dtype=np.float32)
nz_count = int(np.sum(vec > 0))
top_order = np.argsort(-vec)[:8]
top_list = [
{"gene": genes[int(i)], "expr": round(float(vec[int(i)]), 2)}
for i in top_order
if vec[int(i)] > 0
]
summary = {
"dataset": base_dataset,
"cell_idx": 0,
"cell_id": cell_key,
"cell_line": cell_name,
"total_genes": len(genes),
"expressed_genes": nz_count,
"top_baseline_genes": top_list,
"expression_map": expression_map,
}
self.custom_cell_profiles[cell_key] = summary
return summary
def get_cell_baseline_summary(self, dataset: str, cell_idx: int = 0, custom_cell_id: str | None = None) -> dict[str, Any]:
if custom_cell_id and custom_cell_id in self.custom_cell_profiles:
prof = self.custom_cell_profiles[custom_cell_id]
return {k: v for k, v in prof.items() if k != "expression_map"}
if dataset not in ("tahoe", "k562"):
raise ValueError("Unknown dataset.")
cells = self.controls_all[dataset]["cells"]
idx = max(0, min(len(cells) - 1, int(cell_idx)))
vec = np.array(cells[idx]["expression"], dtype=np.float32)
genes = self.genes_by_ds[dataset]
nz_count = int(np.sum(vec > 0))
top_order = np.argsort(-vec)[:8]
top_list = [
{"gene": genes[int(i)], "expr": round(float(vec[int(i)]), 2)}
for i in top_order
if vec[int(i)] > 0
]
cell_line = "A549 Lung Carcinoma" if dataset == "tahoe" else "K562 Chronic Myeloid Leukemia"
return {
"dataset": dataset,
"cell_idx": idx,
"cell_id": cells[idx]["cell_id"],
"cell_line": cell_line,
"total_genes": len(genes),
"expressed_genes": nz_count,
"top_baseline_genes": top_list,
}
def get_gene_graph(self, gene: str, max_spokes: int = 10) -> dict[str, Any]:
sym = gene.strip().upper()
if not GENE_ALLOW_RE.match(sym) or sym not in self.kg:
raise ValueError(f"Unknown human gene symbol: {sym}")
lines = self.kg[sym].strip().splitlines()
partners: list[str] = []
for line in lines[1:]:
parts = line.split()
if len(parts) >= 3 and parts[1] == "functional":
other = parts[2].upper()
if other != sym and other not in partners:
partners.append(other)
if len(partners) >= max_spokes:
break
nodes = [{"id": 0, "elem": sym, "x": 0.0, "y": 0.0, "z": 0.0, "isHub": True}]
edges = []
n = max(1, len(partners))
golden = math.pi * (3.0 - math.sqrt(5.0))
for idx, p_sym in enumerate(partners):
y_norm = 1.0 - (2.0 * (idx + 0.5) / n)
rad_xy = math.sqrt(max(0.0, 1.0 - y_norm * y_norm))
theta = golden * idx
r = 1.65
nodes.append({
"id": idx + 1,
"elem": p_sym,
"x": round(math.cos(theta) * rad_xy * r, 4),
"y": round(y_norm * r * 0.85, 4),
"z": round(math.sin(theta) * rad_xy * r, 4),
"isSpoke": True,
})
edges.append({"a": 0, "b": idx + 1, "order": 1, "dashed": True})
return {
"mode": "crispr",
"gene": sym,
"total_edges": max(0, len(lines) - 1),
"partners": partners,
"nodes": nodes,
"edges": edges,
}
def start_background_preload(self) -> None:
if IS_ZEROGPU or self.model_load_state in ("loading", "ready"):
return
threading.Thread(target=self.ensure_model_loaded, daemon=True).start()
def get_model_status(self) -> dict[str, Any]:
elapsed = (
round(max(0.0, time.perf_counter() - self.model_load_started_at), 1)
if self.model_load_state == "loading" and self.model_load_started_at > 0
else 0.0
)
return {
"device": self.device,
"dtype": str(self.dtype).replace("torch.", ""),
"state": self.model_load_state,
"elapsed_s": elapsed,
"error": self.model_load_error,
}
def ensure_model_loaded(self) -> None:
if self._model is not None and self._tokenizer is not None:
self.model_load_state = "ready"
return
with self._load_lock:
if self._model is not None and self._tokenizer is not None:
self.model_load_state = "ready"
return
self.model_load_state = "loading"
self.model_load_started_at = time.perf_counter()
self.model_load_error = ""
try:
self._tokenizer = AutoTokenizer.from_pretrained(
self.model_id, token=self.hf_token
)
if self.device == "mps":
try:
model = AutoModelForCausalLM.from_pretrained(
self.model_id,
dtype=self.dtype,
low_cpu_mem_usage=True,
attn_implementation="eager",
token=self.hf_token,
).to("mps")
except Exception:
self.dtype = torch.float16
model = AutoModelForCausalLM.from_pretrained(
self.model_id,
dtype=self.dtype,
low_cpu_mem_usage=True,
attn_implementation="eager",
token=self.hf_token,
).to("mps")
elif self.device == "cuda":
model = AutoModelForCausalLM.from_pretrained(
self.model_id,
dtype=self.dtype,
low_cpu_mem_usage=True,
token=self.hf_token,
).to("cuda")
else:
model = AutoModelForCausalLM.from_pretrained(
self.model_id,
dtype=self.dtype,
low_cpu_mem_usage=True,
token=self.hf_token,
)
self._model = model.eval()
self.model_load_state = "ready"
except Exception as exc:
self.model_load_state = "error"
self.model_load_error = str(exc)
raise
def prepare_cell_and_prompt(
self,
dataset: str,
cell_idx: int,
kind: str,
drug_name: str = "",
smiles: str = "",
concentration_um: float = 0.5,
gene: str = "",
custom_cell_id: str | None = None,
custom_cell: dict[str, float] | None = None,
) -> tuple[np.ndarray, np.ndarray, str, dict[str, Any]]:
if dataset not in ("tahoe", "k562"):
dataset = "tahoe"
genes = self.genes_by_ds[dataset]
_, mean_deltas = self.decoders[dataset]
# Support du profil cellulaire personnalisé (via cache ID ou dictionnaire direct)
if custom_cell_id and custom_cell_id in self.custom_cell_profiles:
expr_map = self.custom_cell_profiles[custom_cell_id]["expression_map"]
ctrl_expr = np.array([float(expr_map.get(g, 0.0)) for g in genes], dtype=np.float32)
elif custom_cell is not None:
ctrl_expr = np.array([float(custom_cell.get(g, 0.0)) for g in genes], dtype=np.float32)
else:
cells = self.controls_all[dataset]["cells"]
if not (0 <= cell_idx < len(cells)):
raise ValueError(f"cell_idx must be between 0 and {len(cells) - 1}.")
ctrl_expr = np.array(cells[cell_idx]["expression"], dtype=np.float32)
mean_vec = np.array([mean_deltas.get(g, 0.0) for g in genes], dtype=np.float32)
baseline = np.maximum(0.0, ctrl_expr + mean_vec)
if kind in ("drug", "cytokine"):
mol_info = parse_smiles_2d(smiles)
safe_name = re.sub(r"[^A-Za-z0-9 \-()_/+]", "", drug_name or "Custom Compound")[:60].strip()
label = "Cytokine / Ligand" if kind == "cytokine" else "Drug name"
perturbation_text = (
f"{label}: {safe_name}\n"
f"Drug SMILES: {mol_info['canonical_smiles']}\n"
f"Concentration: {concentration_um} uM"
)
viz = mol_info
elif kind == "crispr":
sym = gene.strip().upper()
viz = self.get_gene_graph(sym)
kg_sent = self.kg[sym].strip()
perturbation_text = f"Gene knockdown: {kg_sent}"
else:
raise ValueError("kind must be 'drug', 'cytokine', or 'crispr'.")
def top_k_genes(vec: np.ndarray, k: int = 1000) -> str:
order = np.argsort(vec)[::-1]
ranked = [genes[i] for i in order if vec[i] > 0][:k]
return " ".join(ranked)
prompt = (
f"{PREAMBLE}\n\n{perturbation_text}\n\n"
f"Source: {top_k_genes(ctrl_expr)}\n\n"
f"Mean Global prediction: {top_k_genes(baseline)}\n"
"Target: "
)
return ctrl_expr, baseline, prompt, viz
def _build_gene_entry(
self,
signed_sym: str,
g: str,
emit_order: int,
dir_rank: int,
ctrl_val: float,
base_val: float,
pred_val: float,
lfc_val: float,
res_val: float,
) -> dict[str, Any]:
partners: list[str] = []
if g in self.kg:
for ln in self.kg[g].splitlines()[1:6]:
ps = ln.split()
if len(ps) >= 3:
partners.append(ps[2])
if g in GENE_ANNOTATIONS:
loc, nick, desc = GENE_ANNOTATIONS[g]
else:
loc, nick, desc = _infer_fallback_annotation(g, partners)
return {
"rank": emit_order,
"dir_rank": dir_rank,
"sym": signed_sym,
"gene": g,
"loc": loc,
"ctrl_expr": round(ctrl_val, 3),
"base_expr": round(base_val, 3),
"pred_expr": round(pred_val, 3),
"lfc": round(lfc_val, 4),
"residual": round(res_val, 4),
"mean_shift": round(base_val - ctrl_val, 4),
"nick": nick,
"desc": desc,
"partners": partners[:4],
"annotated": g in GENE_ANNOTATIONS,
}
def reconstruct_and_summarize(
self,
dataset: str,
cell_idx: int,
raw_text: str,
ctrl_expr: np.ndarray,
baseline: np.ndarray,
top_n_genes: int = 48,
is_truncated: bool = False,
include_all_genes: bool = False,
custom_cell_id: str | None = None,
) -> dict[str, Any]:
g2i = self.gene_to_idx_by_ds[dataset]
decoder, _ = self.decoders[dataset]
up: list[str] = []
down: list[str] = []
interleaved: list[tuple[str, str, int]] = []
seen: set[str] = set()
for tok in raw_text.split():
if len(tok) < 2 or tok[0] not in ("+", "-"):
continue
sym = tok[1:].upper()
if sym in g2i and sym not in seen:
seen.add(sym)
if tok[0] == "+":
up.append(sym)
interleaved.append(("+" + sym, sym, len(up)))
else:
down.append(sym)
interleaved.append(("-" + sym, sym, len(down)))
residual_vec = np.zeros_like(baseline)
if up or down:
task_oh = [0.0] * 7 + [1.0]
eff_up = float(max(len(up), 550) if is_truncated else len(up))
eff_dn = float(max(len(down), 550) if is_truncated else len(down))
feats: list[list[float]] = []
ctrl_vals: list[float] = []
idxs: list[int] = []
for is_up, g_list in ((1.0, up), (0.0, down)):
for rank, g in enumerate(g_list):
idx = g2i[g]
feats.append([is_up, float(rank), eff_up, eff_dn] + task_oh)
ctrl_vals.append(float(baseline[idx]))
idxs.append(idx)
with torch.no_grad():
deltas = decoder(
torch.tensor(feats, dtype=torch.float32),
torch.tensor(ctrl_vals, dtype=torch.float32),
)
residual_vec[idxs] = deltas.cpu().numpy().flatten()
predicted_expr = baseline + residual_vec
predicted_lfc = predicted_expr - ctrl_expr
all_entries: list[dict[str, Any]] = []
for emit_idx, (signed_sym, g, dir_rank) in enumerate(interleaved):
idx = g2i[g]
all_entries.append(
self._build_gene_entry(
signed_sym=signed_sym,
g=g,
emit_order=emit_idx + 1,
dir_rank=dir_rank,
ctrl_val=float(ctrl_expr[idx]),
base_val=float(baseline[idx]),
pred_val=float(predicted_expr[idx]),
lfc_val=float(predicted_lfc[idx]),
res_val=float(residual_vec[idx]),
)
)
up_entries = sorted(
[e for e in all_entries if e["sym"].startswith("+")],
key=lambda e: (-abs(e["residual"]), e["dir_rank"]),
)
down_entries = sorted(
[e for e in all_entries if e["sym"].startswith("-")],
key=lambda e: (-abs(e["residual"]), e["dir_rank"]),
)
half = max(12, top_n_genes // 2)
combined = sorted(
up_entries[:half] + down_entries[:half],
key=lambda e: -abs(e["residual"]),
)[:top_n_genes]
cell_meta = self.get_cell_baseline_summary(dataset, cell_idx, custom_cell_id=custom_cell_id)
verdict = self._synthesize_verdict(
dataset=dataset,
cell_label=cell_meta["cell_line"],
up_entries=up_entries,
down_entries=down_entries,
count_up=len(up),
count_down=len(down),
)
out_payload: dict[str, Any] = {
"dataset": dataset,
"cell_idx": cell_idx,
"cell_id": cell_meta["cell_id"],
"cell_line": cell_meta["cell_line"],
"total_genes": cell_meta["total_genes"],
"count_up": len(up),
"count_down": len(down),
"verdict": verdict,
"top_up": up_entries[:12],
"top_down": down_entries[:12],
"gene_stars": combined,
}
if include_all_genes or not is_truncated:
out_payload["all_genes"] = up_entries + down_entries
return out_payload
def _synthesize_verdict(
self,
dataset: str,
cell_label: str,
up_entries: list[dict[str, Any]],
down_entries: list[dict[str, Any]],
count_up: int,
count_down: int,
) -> dict[str, Any]:
lead_up = ", ".join(f"{e['sym']} ({e['nick']})" for e in up_entries[:2]) or "none"
lead_dn = ", ".join(f"{e['sym']} ({e['nick']})" for e in down_entries[:2]) or "none"
return {
"badge": f"{count_up + count_down} Gene Knobs Shifted",
"headline": f"CellGemma Predicted {count_up} Upregulated (+) and {count_down} Downregulated (-) Genes",
"summary": f"Inside this {cell_label}, top increases are {lead_up} and top decreases are {lead_dn}.",
"featured_up": [e["sym"] for e in up_entries[:1]],
"featured_down": [e["sym"] for e in down_entries[:1]],
}
def stream_predict(
self,
dataset: str,
cell_idx: int,
kind: str,
drug_name: str = "",
smiles: str = "",
concentration_um: float = 0.5,
gene: str = "",
custom_cell_id: str | None = None,
custom_cell: dict[str, float] | None = None,
max_new_tokens: int = 180,
temperature: float = 0.0,
) -> Iterator[dict[str, Any]]:
ctrl_expr, baseline, prompt, input_viz = self.prepare_cell_and_prompt(
dataset=dataset,
cell_idx=cell_idx,
kind=kind,
drug_name=drug_name,
smiles=smiles,
concentration_um=concentration_um,
gene=gene,
custom_cell_id=custom_cell_id,
custom_cell=custom_cell,
)
hw_map = {"mps": "Apple Metal GPU (MPS)", "cuda": "NVIDIA CUDA GPU", "cpu": "Multi-Core CPU"}
hw_label = hw_map.get(self.device, self.device.upper())
dtype_label = str(self.dtype).replace("torch.", "")
if self._model is None or self._tokenizer is None:
load_t0 = time.perf_counter()
if IS_ZEROGPU:
self.ensure_model_loaded()
else:
self.start_background_preload()
while self.model_load_state == "loading" or (
self.model_load_state == "not_loaded" and self._model is None
):
elapsed_load = round(time.perf_counter() - load_t0, 1)
yield {
"type": "heartbeat",
"step": 1,
"phase": "loading_model",
"device": hw_label,
"elapsed_s": elapsed_load,
"message": f"Loading CellGemma E4B weights onto {hw_label} ({dtype_label})... {elapsed_load:.1f}s",
"input_viz": input_viz,
}
time.sleep(0.4)
if self.model_load_state == "error" or self._model is None:
raise RuntimeError(self.model_load_error or "Failed to load CellGemma E4B weights.")
assert self._model is not None and self._tokenizer is not None
with self._model_lock:
formatted = f"<bos><|turn>user\n{prompt}<turn|>\n<|turn>model\n"
inputs = self._tokenizer(
formatted, return_tensors="pt", add_special_tokens=False
).to(self.device)
prompt_tok_len = int(inputs["input_ids"].shape[1])
eot_id = self._tokenizer.convert_tokens_to_ids("<turn|>")
streamer = TextIteratorStreamer(
self._tokenizer, skip_prompt=True, skip_special_tokens=True
)
capped_max = max(32, min(1024, int(max_new_tokens)))
temp_val = max(0.0, min(1.5, float(temperature)))
gen_kwargs: dict[str, Any] = dict(
**inputs,
streamer=streamer,
max_new_tokens=capped_max,
do_sample=temp_val > 0.01,
pad_token_id=self._tokenizer.pad_token_id,
eos_token_id=[self._tokenizer.eos_token_id, eot_id],
)
if temp_val > 0.01:
gen_kwargs["temperature"] = temp_val
chunk_q: queue.Queue[str | None] = queue.Queue()
gen_error: list[Exception] = []
def _run_gen() -> None:
try:
with torch.no_grad():
self._model.generate(**gen_kwargs)
except Exception as exc:
gen_error.append(exc)
finally:
try:
streamer.end()
except Exception:
pass
def _pump_streamer() -> None:
try:
for piece in streamer:
if piece:
chunk_q.put(piece)
finally:
chunk_q.put(None)
start_t = time.perf_counter()
worker = threading.Thread(target=_run_gen, daemon=True)
pumper = threading.Thread(target=_pump_streamer, daemon=True)
worker.start()
pumper.start()
yield {
"type": "started",
"step": 2,
"phase": "encoding_cell",
"device": hw_label,
"prompt_tokens": prompt_tok_len,
"max_new_tokens": capped_max,
"input_viz": input_viz,
"message": f"Encoding Single Cell #{cell_idx} ({prompt_tok_len:,} tokens) on {hw_label}...",
}
accumulated_chunks: list[str] = []
last_reconstruct_tokens = 0
first_token_seen = False
while True:
try:
piece = chunk_q.get(timeout=0.4)
except queue.Empty:
elapsed = round(time.perf_counter() - start_t, 1)
if not first_token_seen:
yield {
"type": "heartbeat",
"step": 2,
"phase": "encoding_cell",
"device": hw_label,
"prompt_tokens": prompt_tok_len,
"elapsed_s": elapsed,
"message": f"Reading 1,000 baseline cell genes & perturbation ({prompt_tok_len:,} tokens)... {elapsed:.1f}s",
}
continue
if piece is None:
break
first_token_seen = True
accumulated_chunks.append(piece)
full_text = "".join(accumulated_chunks)
words = full_text.split()
if not full_text.endswith((" ", "\n")) and words:
complete_words = words[:-1]
else:
complete_words = words
toks = [t for t in complete_words if len(t) >= 2 and t[0] in ("+", "-")]
elapsed = max(1e-3, time.perf_counter() - start_t)
if len(toks) >= 1 and (last_reconstruct_tokens == 0 or len(toks) - last_reconstruct_tokens >= 2):
last_reconstruct_tokens = len(toks)
partial_state = self.reconstruct_and_summarize(
dataset=dataset,
cell_idx=cell_idx,
raw_text=" ".join(toks),
ctrl_expr=ctrl_expr,
baseline=baseline,
is_truncated=True,
custom_cell_id=custom_cell_id,
)
latest_sym = toks[-1]
bare_latest = latest_sym[1:].upper()
latest_nick = GENE_ANNOTATIONS.get(bare_latest, ("cytoplasm", "Gene Shift", ""))[1]
yield {
"type": "partial",
"step": 3,
"phase": "streaming_genes",
"device": hw_label,
"elapsed_s": round(elapsed, 2),
"tok_per_s": round(len(toks) / elapsed, 1),
"gene_count": len(toks),
"latest_gene": {"sym": latest_sym, "nick": latest_nick},
"recent_tokens": toks[-8:],
"state": partial_state,
}
worker.join()
pumper.join()
if gen_error:
raise RuntimeError(f"Model generation failed on {hw_label}: {gen_error[0]}") from gen_error[0]
total_elapsed = max(1e-3, time.perf_counter() - start_t)
final_text = "".join(accumulated_chunks).strip()
gen_subword_count = len(self._tokenizer.encode(final_text, add_special_tokens=False))
hit_cap = gen_subword_count >= int(capped_max * 0.85) and int(capped_max) < 2048
final_state = self.reconstruct_and_summarize(
dataset=dataset,
cell_idx=cell_idx,
raw_text=final_text,
ctrl_expr=ctrl_expr,
baseline=baseline,
is_truncated=hit_cap,
include_all_genes=True,
custom_cell_id=custom_cell_id,
)
final_toks = final_state["count_up"] + final_state["count_down"]
yield {
"type": "complete",
"step": 4,
"phase": "complete",
"device": hw_label,
"elapsed_s": round(total_elapsed, 2),
"tok_per_s": round(max(1, final_toks) / total_elapsed, 1),
"prompt_tokens": prompt_tok_len,
"prompt": prompt,
"raw_text": final_text,
"input_viz": input_viz,
"state": final_state,
}